描述
给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
数据范围: n≤1000
要求:空间复杂度 O(1) ,时间复杂度 O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:
示例1
输入:{1,2,3}
返回值:{3,2,1}
示例2
输入:{}
返回值:{}
说明:
空链表则输出空
------------------------------------------------------------------------
解题思路:
1.使用辅助节点
提供一个新的头结点pre,反转的过程就是逐步将pre挂在拆下来的head上,然后pre成为新链表的头结点,重复直到最后一个节点。时间复杂度O(n)空间复杂度O(1)
public static ListNode ReverseList(ListNode head) {
ListNode pre = null;
while (head != null) {
// 存储临时节点,使head每次后移
ListNode temp = head.next;
// pre挂在head上,此时head已经脱离原链表
head.next = pre;
// pre成为新链表的头
pre = head;
// 将head后移
head = temp;
}
return pre;
}
2.使用栈结构
利用栈的先进后出,将链表元素存入栈,然后依次取出挂在新链表上,时间复杂度O(n)空间复杂度O(n)
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
Stack<ListNode> stack = new Stack();
while (head != null) {
stack.push(head);
head = head.next;
}
if(stack.isEmpty())return null;
ListNode node= stack.pop();
pre = node;
while (!stack.isEmpty()){
node.next= stack.pop();
node = node.next;
}
node.next = null;
return pre;
}