Skip to the content.

Ex24 反转链表

题目描述

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

解题思路

这是一道基础题了,就不再赘述了。

代码

struct ListNode *
reverseList (struct ListNode *head)
{
  if (!head)
    return head;
  struct ListNode *prev = NULL, *cur = head, *next = head->next;
  while (next)
    {
      cur->next = prev;
      prev = cur;
      cur = next;
      next = next->next;
    }
  cur->next = prev;
  return cur;
}

结果

执行结果:通过

执行用时:4 ms, 在所有 C 提交中击败了86.75%的用户

内存消耗:6.2 MB, 在所有 C 提交中击败了26.58%的用户