Swap Nodes in pairs:https://leetcode.com/problems/swap-nodes-in-pairs/
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.
Note: First draw a clear idea, and then start to write code.
P->t->q: Swap t and Q, but be aware that P
key points : It must be noted that after swapping, p->q->t, so the new p should point to T
/** * Definition forsingly-linked list. * struct ListNode {* int val; * ListNode *Next; * ListNode (int x): Val (x),Next(NULL) {} * }; */class Solution {public:listnode* swappairs (listnode* head) {if(Head = =NULL|| Head->Next==NULL)returnHead listnode* dummy = new ListNode (-1); Dummy->Next= head; listnode* p = dummy; while(P && p->Next&& p->Next-Next) {listnode* T = p->Next; listnode* q = p->Next-Next; P->Next= q; T->Next= q->Next; Q->Next= t; p = t; Note that at this point, T has been swapped to the back of Q}returnDummy->Next; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode | Swap Nodes in Pairs in a linklist