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.
思路:将链表拆分,然后再合并
List *swapPairs(List *head) {
if(head == NULL || head->next == NULL)
return head;
List* ji=head;
List* ou = head->next;
List* temp1,*temp2;
List* l1= head;
List* l2 = head->next;
temp1 = l2->next;
while(temp1 != NULL)
{
temp2 = temp1->next;
l1->next = temp1;
l2->next = temp2;
l1 = temp1;
l2 = temp2;
if(l2 !=NULL)
temp1 = l2->next;
else
temp1 = NULL;
}
if(l1 != NULL)
l1->next =NULL;
if(l2 != NULL)
l2->next = NULL;
temp1 = ou;
while(temp1 != NULL&&temp1->next != NULL)
{
temp2 = ji->next;
ji->next = temp1->next;
temp1->next = ji;
temp1 = ji->next;
ji = temp2;
}
temp1->next = ji;
return ou;
}
上面的思路是将一个链表拆分然后再合并,这里仍然使用一个新的节点来作为指引节点来操作。
List* SwapNode(List* list)
{
List* head=new List;
head->next = list;
List* cur = head;
List* pre,*next;
while(cur->next != NULL && cur->next->next != NULL)
{
pre = cur->next;
next = cur->next->next;
cur->next = next;
next = next->next;
cur->next->next = pre;
pre->next = next;
cur = pre;
}
return head->next;
}
ps:其实问题的思路非常的简单,但是解决问题的方法决定了处理问题的简易程度,比如我们始终使用一个指针的next域来指向准备反转的一对指针的第二个指针,然后再反转这对指针即可,这里使用一个伪指针来处理这个问题非常的合适。