【LeetCode】 Rotate List 循环链表

题目: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>


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值