//主要复习栈的先入后出 还有学习一下java中的链条ListNode
描述
给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
数据范围: n≤1000n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
示例1
输入:
{1,2,3}
返回值:
{3,2,1}
示例2
输入:
{}
返回值:
{} 说明:
空链表则输出空
方法一:存入栈中再取出
在Java中我们需要自己定义一个链表的类来生成对象,这个类需要有一个存储数据的数据域也需要有存储下一个节点地址的域。
Java中没有指针只能引用。链条的最后一个的next属性必须规定为null,否则会形成环。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
Stack<ListNode> stack = new Stack<>();
if(head == null)
return null;
while(head != null) {
stack.push(head);
head = head.next;
}
ListNode node = stack.pop();
ListNode dummy = node;
while(!stack.isEmpty()) {
ListNode tempNode = stack.pop();
node.next = tempNode;
node = node.next;
}
node.next = null;
return dummy;
}
}
方法二:改变链条指向
public class Solution {
public ListNode ReverseList(ListNode head) {
if (null == head) return null;
ListNode current = head;
while (current.next != null) {
// 拿到当前节点的 ① 节点
ListNode node = current.next;
// 将当前节点指向 ② 节点
current.next = node.next;
// 将 ① 节点指向头节点
node.next = head;
// 将 ①节点变更为头节点
head = node;
}
return head;
}
}