Yu's Coding Garden : leetcode Question 108: Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
For example,Given a linked list, swap every two adjacent nodes and return its head.
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.
http://blog.csdn.net/linhuanmars/article/details/19948569
这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
public ListNode swapPairs(ListNode head) {
if(head == null) return null; ListNode helper = new ListNode(0); helper.next = head; ListNode pre = helper; ListNode cur = head; while(cur!=null && cur.next!=null) { ListNode next = cur.next.next; cur.next.next = cur; pre.next = cur.next; if(next!=null && next.next!=null) cur.next = next.next; else cur.next = next; pre = cur; cur = next; } return helper.next; }
ListNode *swapPairs(ListNode *head) {
ListNode *p =
new
ListNode(0);
p->next = head;
head = p;
while
(
true
){
if
(p->next==NULL){
break
;}
if
(p->next->next==NULL){
break
;}
ListNode* q1 = p->next;
ListNode* q2 = q1->next;
q1->next = q2->next;
q2->next = q1;
p->next = q2;
p=q1;
}
return
head->next;
}
http://comproguide.blogspot.com/2013/11/pair-swapping-in-linked-list.html
Read full article from Yu's Coding Garden : leetcode Question 108: Swap Nodes in Pairs