How to implement C++ switching nodes in pairs
This article mainly explains "how C++ can achieve paired switching nodes". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn how C++ can achieve pairwise switching nodes.
Swap Nodes in Pairs paired switching nodes
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list "s nodes, only nodes itself may be changed.
Example:
Given
1-> 2-> 3-> 4
, you should return the list as
2-> 1-> 4-> 3.
This problem is not difficult, it is a basic linked list operation problem, which can be realized by recursion and iteration respectively. For iterative implementation, you still need to set up dummy nodes. Note that when you connect the nodes, you'd better draw a graph so as not to confuse yourself. See the code below:
Solution 1:
Class Solution {public: ListNode* swapPairs (ListNode* head) {ListNode* dummy = new ListNode (- 1), * pre = dummy; dummy- > next = head; while (pre- > next & & pre- > next- > next) {ListNode* t = pre- > next- > next; pre- > next- > next = t-> next; t-> next = pre- > next; pre- > next = t Pre = t-> next;} return dummy- > next;}}
The writing of recursion is more concise, actually using the idea of backtracking, recursively traversing to the end of the linked list, then swapping the last two, and then switching forward in turn:
Solution 2:
Class Solution {public: ListNode* swapPairs (ListNode* head) {if (! head | |! head- > next) return head; ListNode* t = head- > next; head- > next = swapPairs (head- > next- > next); t-> next = head; return t;}}
Solution 3:
Class Solution {public ListNode swapPairs (ListNode head) {if (head = = null | | head.next = = null) {return head;} ListNode newHead = head.next; head.next = swapPairs (newHead.next); newHead.next = head; return newHead }} Thank you for your reading. the above is the content of "how C++ can achieve paired switching nodes". After the study of this article, I believe you have a deeper understanding of how C++ can achieve paired switching nodes. the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!