在C语言中,如何在不交换数据的情况下交换链表中的节点?

在C语言中,如何在不交换数据的情况下交换链表中的节点?,c,linked-list,nodes,swap,doubly-linked-list,C,Linked List,Nodes,Swap,Doubly Linked List,我使用这个排序函数,但我不知道如何交换节点地址而不是值。我使用双链表 多谢各位 void sort(LISTnode **h) { LISTnode * start, * min, * temp; int num; start = *h; while (start->next != NULL) { temp = start; min = temp; temp = temp->next;

我使用这个排序函数,但我不知道如何交换节点地址而不是值。我使用双链表

多谢各位

void sort(LISTnode **h) {
    LISTnode * start, * min, * temp;
    int num;
    start = *h;
    while (start->next != NULL) {
        temp = start;
        min = temp;
        temp = temp->next;

        while (temp != NULL) {
            if (temp->number < min->number)
                min = temp;
                temp = temp->next;
        }

        // This part of the code
        num = min->number;
        min->number = start->number;
        start->number = num;

        start = start->next;
    }    
}
void排序(列表节点**h){
LISTnode*开始,*分钟,*温度;
int-num;
开始=*h;
while(开始->下一步!=NULL){
温度=启动;
最小值=温度;
温度=温度->下一步;
while(temp!=NULL){
如果(临时->编号<最小->编号)
最小值=温度;
温度=温度->下一步;
}
//这部分代码
num=min->number;
最小->编号=开始->编号;
开始->编号=num;
开始=开始->下一步;
}    
}
交换两个节点(编辑:非相邻节点!-需要进行特殊处理,因为下面的代码会将部分涉及的下一个/上一个指针设置回相邻节点上自己的对象!!!):

现在节点更改了其在列表中的位置,需要调整节点本身:

tmp = x->prev;
x->prev = y->prev;
y->prev = tmp;

tmp = x->next;
x->next = y->next;
y->next = tmp;
最后:调整头部指针:

if(list->head == x)
{
    list->head = y;
}
else if(list->head == y)
{
    list->head = x;
}
完成

好吧,只做了一半:上面的应用是一个双重的循环链接列表(你可以通过
list->head->previous
获得尾部)。如果您没有循环链接列表,请在第一个代码段添加适当的空指针检查(第二个代码段您不需要,假设x和y都不是空的…),并对尾部进行头部调整

旁注:由于必须调整头部(和尾部,如果需要的话),没有节点的父列表,您无法安全地交换

不过,这需要大量的指针调整。我宁愿考虑在节点内交换数据(尽管被明确排除在你的问题中!)。如果因为数据大而不想这样做,那么考虑将数据单独存储在节点上,并让节点具有指向数据的指针。交换就是交换两个指针,甚至不需要父对象列表对象…

替代方法..
使用双指针交换指针比使用指针进行操作更容易

void swap(Node* &a,Node* &b){
    Node* c=a,a=b,b=c;
}

void swapNodes(Node** head_ref, int x, int y)
{
    Node**a=NULL,**b=NULL;
    Node* head=*head_ref;
    while(head!=NULL){
        if(head->data==x)   *a=head;
        else if(head->data==y)  *b=head;
    }  
    if(a&&b){
        swap(*a,*b);
        swap((*a)->next,(*b)->next);
    }
}

为了交换节点,您需要将上一个节点切换到要交换的节点,因为必须调整它们的下一个指针。欢迎使用StackOverflow。请参加“学会问好问题”stackoverflow.com/help/how-to-ask,做一个a。如果x和y恰好是正确的,这将非常失败adjacent@joop哦,是的,你说得太对了。。。添加了一个提示-这是一个关于数据交换的更多论点,正如我在结论中所建议的那样…问题是,如何做到“不交换数据”。
void swap(Node* &a,Node* &b){
    Node* c=a,a=b,b=c;
}

void swapNodes(Node** head_ref, int x, int y)
{
    Node**a=NULL,**b=NULL;
    Node* head=*head_ref;
    while(head!=NULL){
        if(head->data==x)   *a=head;
        else if(head->data==y)  *b=head;
    }  
    if(a&&b){
        swap(*a,*b);
        swap((*a)->next,(*b)->next);
    }
}