标签:
https://oj.leetcode.com/problems/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.
解题思路:
这时一个稍微复杂点的基本题目,需要用三个变量。需要注意的是,frontNode != null的判断。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head == null){ return null; } //留作返回的引用,如果只有一个节点,就返回head,否则返回第二个元素 ListNode returnNode = head.next == null ? head : head.next; ListNode frontNode = head; ListNode tailNode = head.next; //tempNode用来暂存2-1-3-4状态下的1,此时temp=1,front=3,tail=4 ListNode tempNode = null; while(frontNode != null && tailNode != null){ frontNode.next = tailNode.next; tailNode.next = frontNode; if(tempNode !=null){ //第一次循环temp为空,不执行,用上面的例子,此时状态为2-1(4)-3 //temp=1,front=3,tail=4,所以需要将1指向4(原来指向3) tempNode.next = tailNode; } //2-1-4-3-5-6的情况下,将temp变成3,front变成5,tail变成6 tempNode = frontNode; frontNode = frontNode.next; //这里需要判断,很可能是2-1-4-3-5的情况,front.next已经为空了 if(frontNode != null){ tailNode = frontNode.next; }else{ // return returnNode; } } return returnNode; } }
原题要求用常数的空间,但是本题也有一个递归的方法,虽然用了O(n)的空间,但是更为简洁,思路也不可谓不巧妙,值得体会。
public class Solution { public ListNode swapPairs(ListNode head) { if ((head == null)||(head.next == null)) return head; ListNode n = head.next; head.next = swapPairs(head.next.next); n.next = head; return n; } }
标签:
原文地址:http://www.cnblogs.com/NickyYe/p/4268724.html