给你单链表的头节点 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
一下子没思路, 然后想着用最简单的循环遍历呗 .
略思索了一下 ,
废掉的代码... 没写无 , 写不下去了, 太没技术含量了...... , 渣渣, 没眼看...
public class LeeCode {
@Test
public void reverseBetween(){
ListNode head = new ListNode();
head.init();
int left =2;
int right = 4;
ListNode n = head;
int x = 0;
ListNode start = null;
ListNode end = null;
Stack<ListNode> stack = new Stack<>();
for(int i = 1;i<=right;i++){
if(i+1 == left){
start = n;
}
if(i == left){
stack.push(n);
}else if(i + 1 == right){
stack.push(n);
stack.push(n.next);
end = n.next.next;
break;
}else if(!stack.empty()){
stack.push(n);
}
n=n.next;
}
n = null;
while (stack.size() > 0 && stack.peek() != null){
if(n != null){
n.next = stack.pop();
}else{
n = stack.pop();
}
}
start.next = n;
n.next = end;
System.out.println(start.val);
System.out.println(end.val);
while(start != null){
System.out.println(start.val);
if(start.next == null){
break;
}
}
}
class ListNode {
int val;
ListNode next;
@Override
public String toString() {
return ""+val;
}
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public void init(){
ListNode five = new ListNode(5);
ListNode fore = new ListNode(4,five);
ListNode three = new ListNode(3,fore);
ListNode two = new ListNode(2,three);
this.val = 1;
this.next = two;
}
}
}
然后看了下高级答案:
T-T ... 妈耶.. 高级答案看都看不懂... 捋了半天也没明白. 引用关系有点深, 还是循环更新 . .. 好好看看
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for(int i = 1; i < m; i++){
pre = pre.next;
}
head = pre.next;
for(int i = m; i < n; i++){
ListNode nex = head.next;
head.next = nex.next;
nex.next = pre.next;
pre.next = nex;
}
return dummy.next;
}
}
- 这也是个不错的答案:
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode superior = dummyHead;
// 1. 遍历至m的前一个节点
for ( int i = 1; i < m; i ++ ) {
superior = superior.next;
}
ListNode prev = null;
ListNode cur = superior.next;
// 2. 180°旋转爆炸
for ( int i = 0; i <= n-m; i ++ ) {
ListNode next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
// 3. 修改m和n-m位置处的节点的指向
superior.next.next = cur;
superior.next = prev;
return dummyHead.next;
}
}
网友评论