一、题目
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
二、思路
(1)递归
(2)基于栈,先进后出,比较好想,但是时间上比递归差点。
递归思想的图是这样的:首先递归到单链表的倒数第二个节点,然后将最后一个节点指向倒数第二个,并将这两个当做新的P进行规划下一轮。
三、代码
1、递归
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next=null;
return p;
}
2、基于栈
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null) return head;
Stack<ListNode> queue = new Stack<>();
while(head!=null) {
queue.add(head);
head = head.next;
}
ListNode ans = queue.peek();
ListNode returns = ans;
while(!queue.isEmpty()) {
ans.next = queue.pop();
ans = ans.next;
}
ans.next = null;
return returns;
}