简体   繁体   English

在链表中交换2个节点C ++

[英]swapping 2 nodes in a linked list c++

我试图交换一个链表中的2个相邻节点(在本例中为75和9),每次运行代码时,说一个链表75-> 9-> 767-> 2 ...,我得到的整个列表只是转到75-> 9-> 75-> 9-> 75-> 9等。我必须更新指针

Your problem is with the lines 你的问题是线

nextPtr->next = tempPtr; nextPtr = tempPtr;

I'm not sure, but i think you only mean to type 我不确定,但我认为您只想输入

nextPtr = tempPtr;

instead. 代替。

Hint: If you want to swap nodes H (what you're calling hdList) and N (nextPtr) in a linked list you have to make whatever points to H now point to N. You're not keeping track of whatever points to H at all. 提示:如果要交换链表中的节点H(您称为hdList)和节点N(nextPtr),则必须将指向H的任何点现在指向N。您无法跟踪指向H的任何点完全没有

That is, suppose you know that part of your list is 也就是说,假设您知道列表的一部分是

...   P -> H -> N -> Q ...

and you want to swap H and N. The state of the list after the swap should be 并且您想要交换H和N。交换之后列表的状态应为

...  P -> N -> H -> Q ... 

right? 对? But you can't do this because you don't know what used to point to H (ie P) so you can make it point to N. 但是您不能这样做,因为您不知道曾经指向H的原因(即P),因此可以使其指向N。

I think you're going to have to go back to the drawing board on this one. 我认为您将不得不回到这一方面。

If you want to swap 2 nodes in linked list, why are you trying to swap the pointers and all? 如果要交换链表中的2个节点,为什么要交换指针和所有指针? Just swap the data in it with the simple swap logic. 只需使用简单的交换逻辑交换其中的数据即可。 let the pointers be as it is. 让指针保持原样。 If this is not what you want, tell me in detail what exactly you want it to be. 如果这不是您想要的,请详细告诉我您想要的是什么。

I guess you are looking for pairwise swap, use this for the same. 我猜您正在寻找成对交换,将其用于相同目的。 Let me know if it went fine. 让我知道是否顺利。 for 75->9->767->2 it produces 9->75->2->762... If you want something different but similar, you can use it and make changes accordingly. 对于75-> 9-> 767-> 2,它会生成9-> 75-> 2-> 762 ...如果您需要其他但相似的内容,则可以使用它并进行相应的更改。 void swap(struct node **head) { if (*head == NULL || (*head)->next == NULL) return; 空隙交换(结构节点**头){如果(*头== NULL ||(*头) - >下一个== NULL)回报;

    struct node *prev = *head;
    struct node *cur = (*head)->next;

    *head = cur;  

    while (true)
    {
        struct node *next = cur->next;
        cur->next = prev; 

        if (next == NULL || next->next == NULL)
        {
            prev->next = next;
            break;
        }

        prev->next = next->next;

        prev = next;
        cur = prev->next;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM