1. 首页
  2. 编程语言
  3. C++ 
  4. C++单链表逆置输出的程序代码分享

C++单链表逆置输出的程序代码分享

上传者: 2023-09-05 02:03:04上传 CPP文件 2.11KB 热度 10次

以下是C++实现单链表逆置输出的代码,供大家参考和使用:

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

Node* reverseLinkedList(Node* head) {
    if (head == NULL || head->next == NULL) {
        return head;
    }
    Node* prev = NULL;
    Node* curr = head;
    Node* next = NULL;
    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}

void printLinkedList(Node* head) {
    Node* temp = head;
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
    cout << endl;
}

int main() {
    Node* head = new Node;
    Node* first = new Node;
    Node* second = new Node;

    // 构建链表
    head->data = 1;
    first->data = 2;
    second->data = 3;
    head->next = first;
    first->next = second;
    second->next = NULL;

    cout << "原链表:";
    printLinkedList(head);

    Node* reversedHead = reverseLinkedList(head);

    cout << "逆置后的链表:";
    printLinkedList(reversedHead);

    return 0;
}
iostream>
下载地址
用户评论