Title:
Given a linked list, swap every, adjacent nodes and return its head.
for example,
given 1->2->3->4
, you should return the list As 2->1->4->3
.
Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.
Ideas:
Swap two nodes using the Insert method. Maintains a pre node that represents the previous node that was inserted. Maintains a cur node that represents the node to be inserted. At the same time constructs a virtual head node Dummyhead, maintains the chain list the head node.
Attention:
1. If the linked list is empty, or if there is only one node, the list is returned.
if (head = = NULL | | head->next = = NULL) return head;
2. Maintenance of three nodes.
listnode* dummyhead = new ListNode (0);d ummyhead->next = head; listnode* cur = head; listnode* pre = Dummyhead;
3. Be aware that when the cur itself points to the last node, it is not processed.
while (cur! = NULL && Cur->next! = null)
complexity: O (N)
AC Code:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *swappairs (ListNode *head) { listnode* dummyhead = new ListNode (0); Dummyhead->next = head; listnode* cur = head; listnode* pre = Dummyhead; if (head = = NULL | | head->next = = NULL) return head; while (cur = null && cur->next! = null) { cur = cur->next; listnode* tmp = cur->next; Save the last node of the insertion point Cur->next = pre->next; Insert the CUR node into pre->next = cur; Pre = cur->next; Move the pre to the next insertion position cur->next->next = tmp; The node after the interchange is connected and the next node of the insertion node cur = tmp; Move cur node } return dummyhead->next; }};
[C + +] leetcode:109 swap Nodes in Pairs (Swap adjacent node locations)