反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
建议递归和非递归都实现一下
非递归
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode pre = null;
ListNode cur = head;
while(cur != null)
{
ListNode newcur = cur.next;//记录cur的下一个节点,防止以后指向上一个时找不到了
cur.next = pre;//指向上一个节点
pre = cur;//让上一个节点的位置前移
cur = newcur;//更新cur ++
}
//跳出循环后 cur是null pre记录的才是最后一个非null的cur
return pre;
}
递归
//递归
public ListNode reverseList1(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode newHead = reverseList1(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
未优化前的非递归代码,展示代码慢慢简略的过程
// now i need 非递归
public ListNode reverseList2(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode pre = null;
ListNode cur = head;
while(cur.next != null)
{
ListNode newcur = cur.next;
cur.next = pre;
pre = cur;
cur = newcur;
}
cur.next = pre;
return cur;
}