题目:
给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
数据范围: n\leq1000n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
原题链接:反转链表_牛客题霸_牛客网
对于这题,我做了3种解法(第三种看了别人的):
(1)传统指针法:
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}
ListNode p = head;
ListNode q = head.next;
p.next = null;
ListNode swap = null;
while(q != null){
//换
swap = q.next;
q.next = p;
//移
p = q;
q = swap;
}
return p;
}
}
(2) 使用栈
要import java.util.Stack;
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}
Stack<ListNode> stack = new Stack<>();
ListNode current = head;
ListNode tail = head;
//入栈
while(current != null){
tail = current.next;
stack.push(current);
current = tail;
}
//记录新的head
tail = stack.peek();
//重连指针
while(!stack.empty()){
current = stack.pop();
if(stack.empty()){
current.next = null;
break;
}
current.next = stack.peek();
}
return tail;
}
(3) 递归
public ListNode ReverseList(ListNode head) {
//递归
//当链表为空时,或者到最后一个结点时返回
if(head==null||head.next==null){
return head;
}
//这里最后一个结点返回为头结点
ListNode temp=ReverseList(head.next);
head.next.next=head;
//这里目的是把原来的头节点的next变为null
head.next=null;
//返回头结点
return temp;
}