Rotate List (Java)

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

注意:这题是rotate 就像是把链表首尾相连,然后向右翻转,所以存在k > length的情况,大于的时候翻转位置相当于是k % length的位置。k % length == length的情况不需要翻转。设两个指针,一个比另一个先走k % length步,然后一起往下走,使得一个走到头的时候,另一个正好走到翻转位置的前一个位置(必须指向前一个位置,因为需要将前一个位置的next置为0)。

Source

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
    	if(head == null || head.next == null) return head;
    	ListNode p = head, q = head;
    	int i, len = 0;
    	while(p != null){
    		p = p.next;
    		len ++;
    	}
    	if(n % len == 0) return head;
    	
    	i = n % len;
    	p = head;
    	while(i > 0){
    		p = p.next;
    		i --;
    	}
    	while(p.next != null){   
    		p = p.next;
    		q = q.next;
    	}
    	p = head;
    	head = q.next;
    	q.next = null;    //***链表变动一定要注意末尾变null
    	q = head;
    	while(q.next != null){
    		q = q.next;
    	}
        q.next = p;
        return head;
    }
}


Test

 public static void main(String[] args){
    	ListNode a = new ListNode(1);
    	a.next = new ListNode(2);
    	a.next.next = new ListNode(3);
    	a.next.next.next = new ListNode(4);
 	    a.next.next.next.next = new ListNode(5);
    	
    	ListNode b = new Solution().rotateRight(a, 1);
    	while(b != null){
    		System.out.println(b.val);
    		b = b.next;
    	}
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值