Title description: Give you the head pointer of the singly linked list and two integers left and right, where left <= right. Please reverse the linked list node from position left to position right, and return to the reversed linked list.

Please refer to LeetCode official website for example description.

Source: LeetCode

###### Solution 1: Use the stack

Otherwise, declare a new head node newHead and declare a stack reverseNodes to put left and right for the node between the positions (for the reverse order):

• Traverse the nodes in head
• Put left into the new linked list once;
• Put the nodes between left and right reverseNodes ;
• Use rightNode record the position of the node after the right position;
• Finally, put reverseNodes into the new linked list once, and then put rightNode at the end of the new linked list.

Finally, return `newHead.next` the linked list after inversion.

``````import com.kaesar.leetcode.ListNode;

import java.util.Stack;

public class LeetCode_092 {
public static ListNode reverseBetween(ListNode head, int left, int right) {
}
// 声明一个新的头节点
// 记录是否已经走过left和right位置
boolean findLeft = false, findRight = false;
// 将left和right之间的节点放入栈中
Stack<ListNode> reverseNodes = new Stack<>();
int count = 1;
if (findLeft && findRight) {
break;
}
if (findLeft) {
if (count == right) {
break;
} else {
}
} else {
if (count == left) {
findLeft = true;
if (count == right) {
findRight = true;
break;
}
} else {
leftNode = leftNode.next;
}
}
count++;
}
// 最后将栈中的节点逆序放入新的链表中
while (!reverseNodes.isEmpty()) {
leftNode.next = reverseNodes.pop();
leftNode = leftNode.next;
}
leftNode.next = rightNode;
}

public static void main(String[] args) {

ListNode result = reverseBetween(head, 1, 2);
while (result != null) {
System.out.print(result.val + " ");
result = result.next;
}
}
}``````
[Daily Message] originally had dreams and unfounded self-confidence, but everything starts here.

1.2k 声望
6.1k 粉丝
0 条评论