天天看点

[链表]BM1-反转链表-简单

  • [牛客网-反转链表](​​https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca​​)

给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

数据范围: 要求:空间复杂度  ,时间复杂度  。

如当输入链表{1,2,3}时,经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。

示例1

输入:

{1,2,3}      

复制返回值:

{3,2,1}      

复制

示例2

输入:

{}      

复制返回值:

{}      

复制说明:

空链表则输出空      
struct ListNode
{
  int val;
  struct ListNode *next;
  ListNode(int x) : val(x), next(nullptr)
  {
  }
};

class Solution
{
public:
  ListNode *ReverseList(ListNode *pHead)
  {
    auto cur_node = pHead;
    ListNode *pre_node = nullptr;
    ListNode *next_node = nullptr;
    while (cur_node != nullptr)
    {
      next_node = cur_node->next;
      cur_node->next = pre_node;
      pre_node = cur_node;
      cur_node = next_node;
    }
    return pre_node;
  }
};      

继续阅读