常见算法 - 链表相关:将链表的尾节点移动到最前位置n次

将链表的尾节点移动到头结点处,再完成后的链表再执行该操作,共执行n次。

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right:0->1->2->NULLrotate 4 steps to the right: 2->0->1->NULL


思路:因为链表是从前往后连接的,每次操作尾节点较麻烦,所以可以把链表反转过来,就变成了将头结点移动到尾节点之后,移动n次,之后再把完成后的链表反转过来就是结果了。同时注意,因为是不停循环移动,所以每size次就又回到原链表了,因为只需要循环n%size次就好了,不然循环n次会超时。如图:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
反转:2->1->0->NULL
rotate 1 steps to the right: 1->0->2->NULL 
rotate 2 steps to the right: 0->2->1->NULL
rotate 3 steps to the right: 2->1->->0NULL
rotate 4 steps to the right: 1->0->2->null
反转回来:2->0->1->null


class Solution {
    
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || k<0){
            return null;
        }
        if(head.next == null){
            return head;
        }
        int count = 1;
        ListNode p = reverseList(head);
        ListNode q = p;
        while(q.next!=null){
            q = q.next;
            count++;
        }
        
        for(int i=0; i < k%count; i++){
            q.next = p;
            q = p;
            p = q.next;
            q.next = null;
        }
        return reverseList(p);
    }
    
    public static ListNode reverseList(ListNode head) {
		if(head == null){
			return null;
		}
		ListNode pre = null;
		ListNode curr = head;
		ListNode next = head.next;
		while(curr.next!=null){
			next = curr.next;
			curr.next = pre;
			pre = curr; 
			curr = next;
		}
		curr.next = pre;
		ListNode res = curr;
		return res;
    }
}

猜你喜欢

转载自blog.csdn.net/b9x__/article/details/80218049