描述
Given a linked list, swap every two 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. You may not modify the values in the list, only nodes itself can be changed.
中文:
交换相邻的节点。
算法必须使用常量空间。不能修改链表的值。
分析:
关键是建立几个指针
p,ppre,pprepre
然后修改这几个指针的位置。
p作为第一个,要交换p和p之后的位置。
pre=p,
p=p->next;
要将 pre和p交换
就必须记录pre之前的那个位置和p之后的位置,也就是pprepre和pnext
则pprepre->next=p;(这个pprepre必须不为空)
p->next=pre;
pre->next=pnext;
这样就实现了位置的互换。
然后重新
将p指向pnext;
pprepre指向pre。
这样就会恢复到上面的算法。
注意初始条件。
当pprepre为空的时候,不要考虑pprepre
返回的head必须是第一个
即当pre==head的时候,head=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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL)
return NULL;
ListNode *pPrePre = NULL;
ListNode *pPre = NULL;
ListNode *p = head;
while(p && p->next)
{
pPre = p;
p = p->next;
ListNode *pNext = p->next;
if (pPre == head)
head = p;
if (pPrePre)
pPrePre->next = p;
p->next = pPre;
pPre->next = pNext;
pPrePre = pPre;
p = pNext;
}
return head;
}
};
本文介绍了一种算法,该算法能在常数空间内交换链表中的每两个相邻节点,并保持链表结构不变。通过使用几个关键指针,如 p、ppre 和 pprepre,文章详细解释了如何实现节点位置的交换而无需改变节点值。
526

被折叠的 条评论
为什么被折叠?



