codeTop100题(2)206. 反转链表

69 阅读1分钟

1. 题目

206. 反转链表

2. 思路

我们可以定义一个前指针(pre),一个后指针(next),这样子我们就有了三个指针分别是pre、head、next,当head不为空的时候:

  1. 将next指向head.next
  2. 将head的next指向pre
  3. pre指向head
  4. head指向next

核心思路是先把指针反转,然后三个指针都往后移一位(这种题目强烈建议画个图)

3. 代码

public ListNode reverseList(ListNode head) {
    ListNode pre = null;
    ListNode next = null;
    while(null != head) {
        next = head.next;
        head.next= pre;
        pre = head;
        head = next;
    }
    return pre;
}