题目描述
输入一个链表,反转链表后,输出链表的所有元素。
其中,链表节点定义为:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
解题思路
- 用栈
- 借助前后指针,逐个反转
- 借助临时头结点,原头结点之后的节点不断移动到临时头结点之后
借助栈,一次入栈,逐个出栈,原头结点中next置为null
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null || head.next == null)return head;
Stack<ListNode> stack = new Stack<ListNode>();
stack.push(head);
ListNode p = head.next;
head.next = null;
while(p != null){
stack.push(p);
p = p.next;
}
head = stack.pop();
p = head;
while(!stack.isEmpty()){
p.next = stack.pop();
p = p.next;
}
return head;
}
}
借助前后指针,逐个反转
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null || head.next==null)return head;
ListNode pre = head;
ListNode cur = head.next;
pre.next = null;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
借助临时头结点
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null)return head;
ListNode tempHead = new ListNode(0);
tempHead.next = head;
ListNode p = head.next;
while(p != null){
head.next = p.next;
p.next = tempHead.next;
tempHead.next = p;
p = head.next;
}
return tempHead.next;
}
}