【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>

世上再美的风景,都不及回家的那段路。

【LeetCode】 Rotate List 循环链表

相关文章:

你感兴趣的文章:

标签云: