1、这种倒置的问题一半都要重新再选取一个listnode,然后再加上辅助的指针,cur,ret;
2、两个结点两个结点的倒置,间隔的方法为next=ret->next->next;
题目:
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.
思路:
1、选取辅助的listnode进行计算,两个结点两个结点的倒置;
代码:
/**
* 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) {
if(head==NULL || head->next==NULL) return head;
ListNode *helper=new ListNode(0);
ListNode *cur=helper;
ListNode *ret=head;
while(ret && ret->next)
{
ListNode *next=ret->next->next;
cur->next=ret->next;
cur=cur->next;
cur->next=ret;
ret->next=NULL;
cur=ret;
ret=next;
}
if(ret) cur->next=ret;
return helper->next;
}
};