给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
方法:
(1)判断链表,穿针引线即可。
有五步操作:三次穿针,两次移动。
/**
* 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* dummynode = new ListNode(0);
dummynode->next = head;
ListNode* pre = dummynode, *cur = head;
while(cur && cur->next){
ListNode* next = cur->next;
cur->next = next->next; // 一次穿针
next->next = pre->next; // 二次穿针
pre->next = next; // 三次穿针
pre = cur; // 1次移动
cur = cur->next; // 1次移动
}
ListNode* resnode = dummynode->next;
delete dummynode;
return resnode;
}
};