借鉴的是一个评论里的大佬,他就是自己写的,用的栈方法,没什么链接和讲解。看完后觉得很妙。对链表的理解比我熟练和深多了。
个人微改:
import java.util.Stack;
class ListNode{
int val;
ListNode next;
ListNode(){}
ListNode(int val){this.val = val;}
ListNode(int val,ListNode next){this.val = val;this.next = next;}
public void addNode(int e) {
ListNode newNode = new ListNode(e);
if(this.next==null) {
this.next = newNode;
}else {
this.addNode(e);
}
}
public void nodePrint() {
System.out.print(this.val);
while(this.next!=null) {
System.out.print("--->");
System.out.print(this.next.val);
this.next = this.next.next;
}
}
}
class reverse{
public ListNode reverseBetween(ListNode head,int left,int right) {
Stack<ListNode> sk = new Stack<>();
int n = 0;
ListNode node = head;
ListNode ha = null;
while(node!=null) {
n++;
if(n==right) {
ListNode t = node;
ListNode nx = node.next;
ha = t;
for(int i=0;i<(right-left);i++) {
t.next = sk.pop();
t = t.next;
}
t.next = nx;
if(!sk.isEmpty()) {
sk.pop().next = ha;
}
break;
}
sk.push(node);
node = node.next;
}
return left == 1?ha:head;
}
}
public class ReverseLinkedList_II {
public static void main(String args[]) {
String input = "[1,2,3,4,5]";
ListNode head = stringToListNode(input);
ListNode ret = new reverse().reverseBetween(head, 2, 5);
String out = listToString(ret);
System.out.println(out);
}
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1,input.length()-1);
if(input.length()==0) {
return new int[0];
}
String parts[] = input.split(",");
int output[] = new int[parts.length];
for(int index=0;index<parts.length;index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
public static ListNode stringToListNode(String input) {
int[] nodeValues = stringToIntegerArray(input);
ListNode dummyRoot = new ListNode(0);
ListNode ptr = dummyRoot;
for(int item:nodeValues) {
ptr.next = new ListNode(item);
ptr = ptr.next;
}
return dummyRoot.next;
}
public static String listToString(ListNode node) {
if(node==null) {
return "[]";
}
String result = "";
while(node!=null) {
result += Integer.toString(node.val)+",";
node = node.next;
}
return "["+result.substring(0,result.length()-1)+"]";
}
}

这篇博客展示了如何使用栈来实现链表的翻转操作,具体是在链表中翻转指定范围的节点。作者提供了一个名为`reverseBetween`的方法,该方法接收链表头节点和两个整数,分别表示要翻转的开始和结束位置。通过遍历链表并使用栈保存部分节点,实现了在给定范围内反转链表节点的效果。同时,博客还包含了完整的Java代码实现和测试用例。

被折叠的 条评论
为什么被折叠?



