LeetCode24 Swap Nodes in Pairs pair exchange linked list node, leetcode24 exchange chain
Question:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4
, You shoshould return the list2->1->4->3
.
Your algorithm shocould use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Translation:
A linked list is provided to exchange two connected nodes.
Ideas:
It is a node exchange problem. You only need to save the header node and clarify the location of the switch node.
Code:
Public ListNode swapPairs (ListNode head) {ListNode root = new ListNode (0); // create a first node pointing to the linked list and start root. next = head; ListNode pre = root; // The previous node while (head! = Null & head. next! = Null) {ListNode t = head. next. next; pre. next = head. next; pre. next. next = head; head. next = t; pre = head; head = t;} return root. next ;}
Ensure that the node and the next node exist.
Then there is the exchange problem. Suppose the current linked list is 1-> 2-> 3-> 4. First, create a root node, whose next points to the header.
First cycle: pre points to root, head points to 1, to switch 12, first save the next node 3 of 2, represented by t, then make the next Of pre 2 2, that is, the next node of head; the next node of next 2 is 1, so the result is pre. next. next = head. the next part of the last head is 3, that is, head. next = t.
At this time, the linked list is 2-1-3-4. At this time, the pointer jumps 2. That is, pre points to 1 and head points to 3. Then, the system proceeds to realize the exchange in a loop.