LeetCode 24 Swap Nodes in Pair

来源:互联网 发布:易赛软件 编辑:程序博客网 时间:2024/06/06 11:06

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] view plaincopy
  1. public ListNode swapPairs(ListNode head) {  
  2.       ListNode l1 = head;  
  3.       ListNode l0 = null;  
  4.       ListNode l2 = null;  
  5.       if(head==null||head.next==null){  
  6.           return head;  
  7.       }  
  8.       int index =0;  
  9.       while(l1!=null){  
  10.         ListNode l3 = l1;  
  11.         ListNode l4 = l1.next;  
  12.         if(l1.next == null){  
  13.             return l2;//奇数情况  前面置换完后直接返回  
  14.         }  
  15.         l3.next = l4.next;  
  16.         l4.next = l3;  
  17.         l1 = l3.next;  
  18.         if(index!=0){  
  19.         l0.next = l4;  
  20.         }  
  21.         l0 = l3;  
  22.         if(index ==0){  
  23.         l2 = l4;  
  24.         index++;  
  25.         }  
  26.       }  
  27.        return l2;   
  28.     }  
从Discuss看到一个只有8行的代码,本质上也是黑科技,不进行链表操作,只进行遍历和值的交换,本质上和我上一篇博文的做法一致。。。
[cpp] view plaincopy
  1. class Solution {  
  2.     public:  
  3.         ListNode* swapPairs(ListNode* head) {  
  4.            ListNode *p=head;  
  5.            int tmp;  
  6.            while(p&&p->next){  
  7.                tmp=p->val;  
  8.                p->val=p->next->val;  
  9.                p->next->val=tmp;  
  10.                p=p->next->next;  
  11.            }  
  12.            return head;  
  13.         }  
  14.     };  

0 0
原创粉丝点击