c_cpp 交换链接列表中的节点而不交换数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 交换链接列表中的节点而不交换数据相关的知识,希望对你有一定的参考价值。

// https://www.geeksforgeeks.org/swap-nodes-in-a-linked-list-without-swapping-data/
#include <bits/stdc++.h>
using namespace std;

struct linked_list {
    int data;
    struct linked_list* next;
};
typedef struct linked_list node;

void print (node* n) {
    while (n != NULL) {
        cout<< n->data<< "->";
        n = n->next;
    }
}

node* insert(node* head, int n) {
    node* temp = (node*)malloc(sizeof(node*));
    temp->data = n;
    temp->next = head;
    head = temp;
    return head;
}

node* swap (node* head,int x, int y) {
    node *prev1=NULL, *temp1=head, *prev2=NULL, *temp2=head;
    while (temp1 && temp1->data != x){
        prev1 = temp1;
        temp1 = temp1->next;
    }
    while (temp2 && temp2->data != y){
        prev2 = temp2;
        temp2 = temp2->next;
    }

    if (prev1 != NULL)
        prev1->next = temp2;
    else
        head=temp2;
    if (prev2 != NULL)
        prev2->next = temp1;
    else
        head = temp1;
    node* temp = temp1->next;
    temp1->next = temp2->next;
    temp2->next = temp;
    return head;
}

int main() {
    int n,x,y;
    node* head = NULL;
    while (true) {
        cout<< "Enter the elements, and -999 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head=insert(head,n);
    }
    print(head);
    cout<< "Enter x and y: ";
    cin>>x>>y;
    head=swap(head,x,y);
    cout<< "\n";
    print(head);
}

以上是关于c_cpp 交换链接列表中的节点而不交换数据的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 237.删除链接列表中的节点

c_cpp 237.删除链接列表中的节点 - 简单-2018.82

c_cpp 编写一个函数以获取链接列表中的第N个节点

LeetCode Algorithm 1721. 交换链表中的节点

LeetCode Algorithm 1721. 交换链表中的节点

LeetCode Algorithm 1721. 交换链表中的节点