Problem:
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.
In this question, we need to replace each other through node operations, instead of modifying the Val value. This topic mainly refers to the linked list, and determines whether it is clear where it points. This should be taken into consideration. For 1 2 3 4, set a header to point to this table. If it is 0, 0 points to 1, now we want 0 to 2 to 1 to 3 to 4. step by step, assign the next value of 2 to the next value of 1, and then assign 1 to the next value of 2, so that 2 points to 1 and 3. (if 1 is assigned to the Next of 2, 3 is overwritten by 1, and 3 is not found. Therefore, this cannot be done ). We have 2 points to 1 points to 3 points to 4, because 0 points to 1 and has not been changed, so 0 points to 2 at this time, then 0 points to 2 points to 1 points to 3 points to 4, and it is not over yet, because 3 and 4 have not been replaced. Similarly, in this case, we need to give the next of 4 to 3, and then the next of 3 to 4. At this time, isn't it over? No, because 1 points to 3, so we also need to implement next for 4 to 1 (through BEF (that is, before) in the code, every time you assign the BEF value to the second one that has been replaced, and then assign the next replaced header to the Next of BEF, the entire string is ready. Because our header is 0, the next pointer that returns 0 is the answer.
The Code is as follows:
/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: listnode * swappairs (listnode * head) {If (! Head |! (Head-> next) {return head;} listnode * TMP = new listnode (0); listnode * ans = TMP; listnode * BEF = ans; // ensure that ans are directed to the next Binary Group TMP-> next = head; TMP = TMP-> next; while (TMP & (TMP-> next )) {listnode * m = TMP; listnode * nn = TMP-> next; TMP = TMP-> next; m-> next = nn-> next; // For example, 1 2 3, first point 1 to 3, and then 2 to 1. In this case, 2-> 1-> 3 TMP-> next = m; bef-> next = TMP; // The Next part of BEF points to the first TMP = m-> next; BEF = m; // update BEF to the next one of the converted binary groups, to connect to the next Binary Group} return ANS-> next; // The first of ANS is zero, start next is what you want }};
I add a delete ans to the return statement, but it is still accept. This question is small, so the new statement cannot be deleted. What if I want to delete it. What should I do?
Leetcode 23rd -- Swap nodes in pairs