两两交换链表中的节点
描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
思路和代码
题目规定了不允许单纯改变节点内部的值,如果可以直接改变值,那么就会更容易.
- 设置三个节点,pre表示要变换的两个节点的前一个节点
- start表示两个要交换的节点中的第一个,end为后一个
- 交换过程
- pre->next = end;
- start->next = end->next
- end->next = start
- pre = start
/**
* 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 *pre = new ListNode(0);
pre->next = head;
ListNode *temp = pre;
while(temp->next!=NULL && temp->next->next!=NULL)
{
ListNode *start = temp->next;
ListNode *end = temp->next->next;
temp->next = end;
start->next = end->next;
end->next = start;
temp = start;
}
return pre->next;
}
};