当前位置 : 主页 > 编程语言 > java >

Java实现链表反转(借助栈实现)

来源:互联网 收集:自由互联 发布时间:2022-07-22
public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } // 添加新的结点 public void add(int newval) { ListNode newNode = new ListNode(newval); if (this.next == null) this.next = newNode; else this.
public class ListNode {
int val;
ListNode next = null;

ListNode(int val) {
this.val = val;
}

// 添加新的结点
public void add(int newval) {
ListNode newNode = new ListNode(newval);
if (this.next == null)
this.next = newNode;
else
this.next.add(newval);
}

// 打印链表
public void print() {
System.out.print(this.val);
if (this.next != null) {
System.out.print("-->");
this.next.print();
}

}
}

 

import java.util.Stack;

public class ListReverse {
public ListNode ReverseList(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode node = head;
if (head == null) {
return null;
}
while (node != null) {
stack.push(node);
node = node.next;
}
ListNode newHead = new ListNode(stack.pop().val);
ListNode tmp = newHead;
while (stack.size() > 0) {
node = stack.pop();
ListNode newtmp = new ListNode(node.val);
tmp.next = newtmp;
tmp = newtmp;
}
return newHead; // 在最后添加上null作为结束标志
}

public static void main(String[] args) {
ListNode l1 = null; // 创建链表对象 l1 (对应有参 和 无参 构造方法)
if (l1 != null) {
l1.print();
ListReverse lr = new ListReverse();
ListNode reverseList = lr.ReverseList(l1);
System.out.println();
reverseList.print();
}else{

}

}
}

 

唯有热爱方能抵御岁月漫长。



网友评论