LeetCode刷题之反转链表

112 阅读1分钟
  • 反转链表是数据结构中较为简单的题目,其核心是依靠三个中间变量,进行链表的反转
  • 用next记录下一个节点,用pre记录当前节点前一个节点
  • 当前current节点不为空,则进行循环
  • 过程为
    • 假设有A、B、C、D三个节点,此时进行循环,head.next不为空
    • next = head.next;head.next = pre;pre = head;head = next;
    • 假设为A节点,next和pre的初始值都为null;
    • next = head.next;A.next = null;pre = A;A = next;
  • 这里模拟
    • 假设一个链表:A-> B -> C,此时反转为C->B->A
    • head.next = next head.next -> B
      • 然后next = A.next; next -> B next指向B
      • head.next = pre,此时head.next -> null(pre)
      • pre = A, pre -> A,pre指向A
      • head = next, head-> next,head节点指向next(B)
    • 第二次循环
      • next = head.next next -> C
      • head.next = pre B.next -> A
      • pre = head pre-> B
      • head = next head -> C
    • 第三次循环,此时next不为null
      • next = head.next; next -> C.next(null)
      • head.next = pre; c.next -> B
      • pre = head; pre -> C
      • head = next; head -> next
    • 再次判断head为null结束循环
    • 返回pre
  • code
var reverseHead = function (head) {
 if (head === null || head.next === null) {
   return head
 }
 let next = null
 let pre = null
 while(head !== null) {
   next = head.next
   head.next = pre
   pre = head
   head = next
 }
 return pre
}