目录
一、题目要求
给出一个链表 反转它
二、解题思路
使用java的stack的特性 先进后出 遍历链表放入到stack中 然后再放进新的链表中 返回
代码如下(示例):
import java.util.Stack;
/**
* 反转链表
*/
class ListNode {
public int val;
ListNode next = null;
public ListNode(int value) {
this.val = value;
}
}
public class Solution1 {
public static ListNode ReverseList(ListNode head) {
Stack<Integer> stack = new Stack<>();
//遍历单链表
while (head != null) {
stack.push(head.val);
head = head.next;
}
//放入新的链表
ListNode pre =null;
while (!stack.empty()) {
if (pre == null) pre =new ListNode(stack.pop());
else {
//如果pre 不为空 遍历到最后面添加节点
ListNode temp=pre;
while (temp.next!=null){
temp=temp.next;
}
temp.next=new ListNode(stack.pop());
}
}
return pre;
}
public static void main(String[] args) {
ListNode listNode1 = new ListNode(0);
ListNode listNode2 = new ListNode(1);
ListNode listNode3 = new ListNode(2);
ListNode listNode4 = new ListNode(3);
ListNode listNode5 = new ListNode(4);
listNode1.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode4.next = listNode5;
ListNode listNode = ReverseList(listNode1);
//遍历单链表
while (listNode != null) {
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
总结
没咋刷过算法题 慢慢从这里开始吧。
本文详细介绍了如何使用Java的Stack数据结构来实现链表反转,通过示例代码演示了遍历、存储和重构链表的过程,适合初学者入门算法题练习。

216

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



