Swap Nodes in Pairs

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.

 

思路一: 把奇数节点和偶数节点分别保存到链表

注意事项: 注意处理每条链表的尾部节点,保证链表的独立性;另外过程遍历节点时,要注意每个前后节点之间的关系

JAVA 代码:

  1. public ListNode swapPairs(ListNode head) {
  2. if(head==null || head.next==null) return head;
  3. ListNode one = head;
  4. ListNode two = head.next;
  5. ListNode f1 = head;
  6. ListNode f2 = head.next;
  7. ListNode p = f2.next;
  8. while(p!=null) {
  9. f1.next=p;
  10. f1=f1.next;
  11. p=p.next;
  12. if(p!=null) {
  13. f2.next=p;
  14. f2=f2.next;
  15. p=p.next;
  16. }
  17. }
  18. f1.next=null;
  19. f2.next=null;  // 得到奇数链表节点和偶数链表节点,并处理尾部节点的next指针
  20. //one two linklist<ListNode>
  21. ListNode dummy = new ListNode(0);
  22. ListNode tail = dummy;
  23. while(two!=null && one!=null) {
  24. tail.next=two;
  25. tail=tail.next;
  26. two=two.next; // remember the tail points to a object same with two
  27. tail.next=one;
  28. tail=tail.next;
  29. one=one.next;
  30. }
  31. if(one!=null) tail.next=one;
  32. return dummy.next;
  33. }

思路二: 用三个指针指向pre、first、second节点,然后交换first和second节点的内容,遍历一次即可

C++代码:

  1. ListNode *swapPairs(ListNode *head) {
  2. if(head==NULL || head->next==NULL) return head;
  3. ListNode *dummy = new ListNode(-1);
  4. dummy->next=head;
  5. ListNode *pre=dummy;
  6. ListNode *f1=head;
  7. ListNode *s1 = head->next;
  8. int cn=2;
  9. while(s1!=NULL) {
  10. if(cn%2==0) {
  11. f1->next=s1->next;
  12. s1->next=f1;
  13. pre->next=s1;
  14. pre=f1;
  15. f1=pre->next;
  16. cn=0;
  17. s1=pre;
  18. }
  19. s1=s1->next;
  20. cn++;
  21. }
  22. return dummy->next;
  23. }
posted @ 2014-06-29 10:44  purejade  阅读(83)  评论(0)    收藏  举报