From 36d008734766673b767d8dccc55db18e4da04cdd Mon Sep 17 00:00:00 2001 From: yuanguangxin <274841922@qq.com> Date: Thu, 26 Mar 2020 22:49:55 +0800 Subject: [PATCH] add q61 --- .idea/workspace.xml | 61 ++++++++++--------- README.md | 1 + .../q61_旋转链表/ListNode.java | 10 +++ .../q61_旋转链表/Solution.java | 31 ++++++++++ 4 files changed, 73 insertions(+), 30 deletions(-) create mode 100644 src/链表操作/q61_旋转链表/ListNode.java create mode 100644 src/链表操作/q61_旋转链表/Solution.java diff --git a/.idea/workspace.xml b/.idea/workspace.xml index b71213d..248e887 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -1,8 +1,9 @@ - - + + + @@ -67,11 +68,11 @@ + - @@ -264,14 +265,7 @@ - - - - 1580714190854 - 1580753759299 @@ -609,7 +603,14 @@ - @@ -662,7 +663,6 @@ - @@ -687,7 +687,8 @@ - @@ -702,35 +703,35 @@ - + - - - + + + - + - - + + - + - + - + - + - + - + - + @@ -760,10 +761,10 @@ - + - + diff --git a/README.md b/README.md index 846f3a2..079abf6 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ * [q2_两数相加](/src/链表操作/q2_两数相加) * [q19_删除链表的倒数第N个节点](/src/链表操作/q19_删除链表的倒数第N个节点) +* [q61_旋转链表](/src/链表操作/q61_旋转链表) * [q138_复制带随机指针的链表](/src/链表操作/q138_复制带随机指针的链表) * [q206_反转链表](/src/链表操作/q206_反转链表) diff --git a/src/链表操作/q61_旋转链表/ListNode.java b/src/链表操作/q61_旋转链表/ListNode.java new file mode 100644 index 0000000..2254184 --- /dev/null +++ b/src/链表操作/q61_旋转链表/ListNode.java @@ -0,0 +1,10 @@ +package 链表操作.q61_旋转链表; + +public class ListNode { + int val; + ListNode next; + + ListNode(int x) { + val = x; + } +} diff --git a/src/链表操作/q61_旋转链表/Solution.java b/src/链表操作/q61_旋转链表/Solution.java new file mode 100644 index 0000000..f417124 --- /dev/null +++ b/src/链表操作/q61_旋转链表/Solution.java @@ -0,0 +1,31 @@ +package 链表操作.q61_旋转链表; + +/** + * 先连接成环再找断点 o(n) + */ +public class Solution { + + public ListNode rotateRight(ListNode head, int k) { + if (head == null) { + return null; + } + if (head.next == null) { + return head; + } + + ListNode oldTail = head; + int n; + for (n = 1; oldTail.next != null; n++) { + oldTail = oldTail.next; + } + oldTail.next = head; + ListNode newTail = head; + for (int i = 0; i < n - k % n - 1; i++) { + newTail = newTail.next; + } + ListNode newHead = newTail.next; + newTail.next = null; + + return newHead; + } +}