LeetCode 24. Swap Nodes in Pairs(链表题目)
题目描述:
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
思路分析
该题目交换连续的两个节点,由于要动态的改变链表中结点指针的指向,所以说要定义几个结点。分别为需要交换的两个节点node1,node2,以及下一个节点next,需要交换的两个节点的前一个结点也需要标注p,但是由于交换从头结点就开始了,前一个节点是没法有的,所以这里采用了虚拟头结点的思想,很方便的解决的该题目。
具体代码:
/**
* 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(0);
dummy->next=head;
ListNode* p=dummy;
while(p->next&&p->next->next)
{
//需要用到的三个辅助节点
ListNode* node1=p->next;
ListNode* node2=node1->next;
ListNode* next=node2->next;
//改变指针指向,交换两个节点
node2->next=node1;
node1->next=next;
p->next=node2;
//确定新的起始点
p=node1;
}
ListNode* res=dummy->next;
delete dummy; //最好是注意一下,内存清理
return res;
}
};