算法---- 借用栈实现链表反转
题目描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
@Override
public String toString() {
return val+"->"+next;
}
}
public class StackReverseLinkedList {
public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
ListNode c = new ListNode(3);
ListNode d = new ListNode(4);
ListNode e = new ListNode(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
System.out.println(a);
System.out.println(StackReverseList(a));
}
private static ListNode StackReverseList(ListNode node) {
//记录节点的开始位置
ListNode temp=node;
//记录节点的位置
ListNode temp1=node;
Stack<Integer> stack=new Stack<>();
while (node!=null){
stack.push(node.val);
node=node.next;
}
while (!stack.empty()){
temp.val=stack.pop();
temp=temp.next;
}
return temp1;
}
}
运行结果:
1->2->3->4->5->null
5->4->3->2->1->null
- 两轮循环,第一轮循环把链表的值存储到stack中,第二轮循环把stack中的值替换原链表的值。
参考:https://www.cnblogs.com/jiyongjia/p/13193008.html