剑指Offer 24 反转链表
题目描述:
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。LeetCode链接


迭代法
定义三个指针

由于三变量演示图示过于密集,所以动画上只引入两个变量。
public ListNode reverseList(ListNode head)
{
ListNode prev = null;
ListNode cur = head;
ListNode next;
while (cur != null)
{
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
头插法
定义三个指针
-
第一个指针newHead,指向新链表的头节点,最初指向 NULL。 -
第二个指针 cur ,最初指向原始链表头节点head。 -
第三个指针为了保存cur的下一个节点,防止cur指向prev后造成断链。 
public ListNode reverseList(ListNode head)
{
ListNode newHead = null;
ListNode cur = head;
ListNode next;
while (cur != null)
{
next = cur.next;
cur.next = newHead;
newHead = cur;
cur = next;
}
return newHead;
}
|