Description
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.
分析
题目的意思是:成对的交换链表的节点。
- 需要建立dummy节点,然后直接按照题目给的方式在遍历链表的时候进行反转。
代码
/**
* 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) {
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode* pre=dummy;
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;
}
};
参考文献
[LeetCode] Swap Nodes in Pairs 成对交换节点