zoukankan      html  css  js  c++  java
  • 【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>


  • 相关阅读:
    thinkphp3.2v
    ng-select 下拉的两种方式
    angular的时间指令 以及防止闪烁问题
    angularjs中的几种工具方法
    运用正则+replace+substring将一段英语的字母大写 angurlar运用自定义指令filter完成首字母大写
    angularjs bind与model配合双向绑定 表达式方法输出
    ajax跨域问题
    团队作业一
    校外实习报告(四)
    校外实习报告(三)
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/7283636.html
Copyright © 2011-2022 走看看