题目
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围: 0≤n≤1000
要求:空间复杂度 O(1) ,时间复杂度 O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
示例1:
输入:
{1,2,3}
返回值:
{3,2,1}
示例2:
输入:
{}
返回值:
{}
说明:
空链表则输出空
思路:设置next存放第一个值,以及后续移动的值;设置一个头zhuNode存最后一个值的地址,中间的nextValue存下一个地址,next放当前所在位置
换地址到next.next。
保存该next值给zhuNode,将nextValue保存的下一指针值给next,next继续循环。
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null){
return null;
}
int count = 1;
ListNode next = new ListNode(head.val);
next.next = head.next;
ListNode zhuNode = null;
while (next!=null){
// 保存后面的值
ListNode nextValue = next.next;
// 存
next.next = zhuNode;
// 移动位置
zhuNode = next;
next = nextValue;
count++;
}
if(count < 0 || count > 1001){
return null;
}
return zhuNode;
}
}
方法二:采用栈的方式,所以保存首地址Node2的值
// 方法二
Stack<ListNode> stack = new Stack<>();
while (head!=null){
stack.push(head);
head = head.next;
}
// 最后一个值出栈
ListNode node = stack.pop();
ListNode node2 = node;
while (!stack.isEmpty()){
ListNode value = stack.pop();
node.next = value;
node = node.next;
count++;
}
node.next = null;
if(count < 0 || count > 1000){
return null;
}
// node2为最开始的首地址
return node2;