描述
给定一个单链表的头结点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
输入:
{}
返回值:
{}
说明:
空链表则输出空
栈的方式存储,先进后出
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
Stack<Integer> stack = new Stack<>();
if(head == null){
return null;
}
while (head != null) {
stack.add(head.val);
head = head.next;
}
ListNode result = new ListNode(-1);
ListNode move = result;
while (!stack.isEmpty()) {
Integer list = stack.pop();
move.next = new ListNode(list);
move = move.next;
}
return result.next;
}
}
方法二:采用中间结点去反转链表
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode pre = head;
ListNode tail = head.next;
pre.next = null;
while (tail != null) {
ListNode tmp = tail.next;
tail.next = pre;
pre = tail;
tail = tmp;
}
return pre;
}
}
反转链表二 中等难度
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度O(n),空间复杂度 O(1)。
例如:
给出的链表为
1→2→3→4→5→NULL, m=2,n=4,
返回 1→4→3→2→5→NULL.
数据范围: 链表长度 0<size≤1000,0<m≤n≤size,链表中每个节点的值满足 ∣val∣≤1000
要求:时间复杂度 O(n) ,空间复杂度 O(n)
进阶:时间复杂度 O(n),空间复杂度 O(1)
示例1
输入:{1,2,3,4,5},2,4
返回值:{1,4,3,2,5}
示例2
输入:{5},1,1
返回值:{5}
思路:
代码: