旋转链表
题目形容:给你一个链表的头节点 head ,旋转链表,将链表每个节点向右挪动 k 个地位。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:双指针法
- 首先,如果head为null或者head只有一个节点,间接返回head;
遍历链表head失去链表的长度为length,依据
k % length
算得toJump,toJump为理论须要多少位挪到链表后面,如果toJump为0,阐明旋转后不须要移动,间接返回head,如果toJump大于0,则初始化2个节点first和last别离指向头结点,而后利用双指针法,失去须要挪的最初几位,具体处理过程如下:
- 首先将last挪动到链表的第toJump位;
- 而后同时挪动first和last节点,直到last的next不为空为止。
- 最初挪动到last的next为空,此时last即为原链表的最初一个节点,first的next节点为新的头结点,此时,初始化newHead为first的next节点,而后将first的next置空,first为新链表的最初一个节点,而后将last指向原链表的头结点head,最初返回newHead即为旋转后的链表。
public class LeetCode_061 { public static ListNode rotateRight(ListNode head, int k) { if (head == null || head.next == null) { return head; } ListNode cur = head; // 链表的长度 int length = 0; while (cur != null) { length++; cur = cur.next; } // 须要将倒数 toJump 位挪到 head 节点后面 int toJump = k % length; if (toJump == 0) { return head; } ListNode first = head, last = head; while (toJump > 0) { last = last.next; toJump--; } while (last.next != null) { first = first.next; last = last.next; } ListNode newHead = first.next; first.next = null; last.next = head; return newHead; } public static void main(String[] args) { ListNode head = new ListNode(0); head.next = new ListNode(1); head.next.next = new ListNode(2); ListNode listNode = rotateRight(head, 4); while (listNode != null) { System.out.print(listNode.val + " "); listNode = listNode.next; } }}
【每日寄语】 只有你明天再多致力一下,那个将来能够像星星一样闪闪发光的人就是你呀!