反转链表C++

本文详细介绍了如何使用C++实现链表的反转操作,包括ListNode结构定义、reverseList函数实现以及PrintList函数用以展示链表。特别指出在遍历过程中处理最后一个有效节点的注意事项。
摘要由CSDN通过智能技术生成

力扣原题:反转链表

#include<stdio.h>
#include<iostream>
using namespace std;
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };

ListNode* reverseList(ListNode* head) {
    if (head == nullptr) return nullptr;
    ListNode* pre = nullptr;
    ListNode* cur = head;
    while (cur->next != nullptr) {
        ListNode* tmp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = tmp;
    }
    cur->next = pre;
    return cur;
}
void PrintList(ListNode* head) {
    if (head == NULL) {
        std::cout << "NULL" << std::endl;
        return;
    }
    ListNode* cur = head;
    while (cur != NULL) {
        std::cout << cur->val << "->";
        cur = cur->next;
    }
    std::cout << "NULL" << std::endl;
}
  int main() {
      ListNode* n1 = new ListNode(1);
      ListNode* n2 = new ListNode(2);
      ListNode* n3 = new ListNode(3);
      ListNode* n4 = new ListNode(4);
      n1->next = n2;
      n2->next = n3;
      n3->next = n4;
      PrintList(n1);
      PrintList(reverseList(n1));
 }

 注意点:当cur节点遍历到最后一个有效节点的时候,不能再使cur=tmp;因为此时tmp为NULL

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值