C++链表操作示例

Jackey C/C++ 625 次浏览 没有评论
#include <iostream>
#include <set>

using namespace std;

//Definition for singly-linked list.
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* createLinkedList(int arr[], int n) {
    if (n == 0)
        return NULL;

    ListNode* head = new ListNode(arr[0]);

    ListNode* curNode = head;
    for (int i = 1; i < n; ++i) {
        curNode->next = new ListNode(arr[i]);
        curNode = curNode->next;
    }
    return head;
}

// 打印链表
void printLinkedList(ListNode* head) {
    ListNode* curNode = head;
    while (curNode != NULL) {
        cout<<curNode->val<<" -> ";
        curNode = curNode->next;
    }
    cout<<"NULL"<<endl;
    return;
}

// 释放链表
void deleteLinkedList(ListNode* head) {
    ListNode* curNode = head;
    while (curNode != NULL) {
        ListNode* delNode = curNode;
        curNode = curNode->next;
        delete delNode;
    }
    return;
}

class Solution {
public:
    ListNode *reverseList(ListNode *head) {
        ListNode* pre = NULL;
        ListNode* cur = head;
        while (cur != NULL) {
            ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr)/sizeof(int);

    ListNode* head = createLinkedList(arr, n);
    printLinkedList(head);
    ListNode* head2 = Solution().reverseList(head);
    printLinkedList(head2);

    deleteLinkedList(head2);

    return 0;
}

 

发表评论

您的电子邮箱地址不会被公开。

Go