【LeetCode】 Rotate List 迴圈連結串列

HIT_微笑前進發表於2015-03-20

題目:rotate list

解法1:

<span style="font-size:18px;">/**LeetCode Rotate List:Given a list, rotate the list to the right by k places, where k is non-negative.
 * 題目:迴圈移動連結串列,等價於將連結串列從右邊數的k個節點移動到表的前方
 * 思路:移動倒是簡單,重點是要找到連結串列倒數的k個數,就等價於找到倒數第K+1個數,設定兩個指標,先後遍歷連結串列,中間相隔k個數
 * 當前面的指標走到最後的一個節點,此時後面的指標指向的就是倒數第k+1個數
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */ 
package javaTrain;

public class Train14 {
	 public ListNode rotateRight(ListNode head, int k) {
	        ListNode pFast,pSlow,pKnode;
	        int n = 0;
	        
	        if(head == null || k < 1 ) return head;	//注意特殊情況
	        pFast = head;
	        pSlow = head;
	        while(pFast != null){
	        	pFast = pFast.next;
	        	n++;
	        }
	        k = k%n;	//迴圈移動,可以轉變為求模
	        if(k == 0) return head;	//移動的次數等於自己的長度,等價於本身
	        pFast = head;
	        while(k>0 && pFast != null){ 
	        	pFast = pFast.next;
	        	k--;
	        } 
	        while(pFast.next != null){
	        	pFast = pFast.next;
	        	pSlow = pSlow.next;
	        }
	        pKnode = pSlow.next;	//第k+1個節點,次後就是要移到前面的節點了,
	        pSlow.next = null;
	        pFast.next = head;	//原本最後的節點此時排在頭結點之前
	        
	        return pKnode;
	    } 
}
</span>

解法2:

<span style="font-size:18px;">//法2:將連結串列連城環,而後從新尋找新的頭結點和尾節點,即在len-k處
package javaTrain;

public class Train14_1 {
	public ListNode rotateRight(ListNode head, int k) {
		if(head == null || k == 0) return head;	//特殊情況
		ListNode pNode = head;
		int len = 1;
		while(pNode.next != null){
			pNode = pNode.next;
			len++;
		}
		k = len-k%len;
		pNode.next = head;	//注意此時pNode是原來的尾節點
		for(int i = 0;i < k;i++){
			pNode = pNode.next;		
		}
		head = pNode.next;
		pNode.next = null;
		return head;
	}
}
</span>


相關文章