合并两个有序的链表和反转链表

#include<iostream>
#include <vector>
#include <memory>
using namespace std;

struct node {
    int val;
    node* next;
    node(int val) : val(val), next(NULL)  {}
};

node* mergeList(node* a, node* b) {
    if(a == NULL) {
        return b;
    }
    if(b == NULL) {
        return a;
    }
    node jk(0);
    node* vhead = &jk;
    node* cur = vhead;
    while(a != NULL && b != NULL) {
        if(a->val < b->val) {
            cur->next = a;
            a = a->next;
        }else {
            cur->next = b;
            b = b->next;
        }
        cur = cur->next;
    }
    if(a == NULL) {
        cur->next = b;
    }
    if(b == NULL) {
        cur->next = a;
    }
    return vhead->next;
}

node* getList(vector<int>& nums) {
    node jk(0);
    node* vhead = &jk;
    node* cur = vhead;
    int n = nums.size();
    for(int i = 0; i < n; i++) {
        cur->next = new node(nums[i]);
        cur = cur->next;
    }
    cur->next = NULL;
    return vhead->next;
}

void printList(node* c) {
    while(c != NULL) {
        cout << c->val << " ";
        c = c->next;
    }
}

node* reverseList(node* a) {
    node* b = NULL;
    while(a != NULL) {
        node* c = a->next;
        a->next = b;
        if(c == NULL) {
            break;
        }
        b = a;
        a = c;
    }
    return a;
}

int main() {
    // //合并链表
    // vector<int> nums1 = {1, 2, 5, 6, 9, 10};
    // node* a = getList(nums1);
    // vector<int> nums2 = {3, 4, 5, 6, 9,10, 11};
    // node* b = getList(nums2);
    // node* c = mergeList(a, b);
    // while(c != NULL) {
    //     cout << c->val << " ";
    //     c = c->next;
    // }
    //反转链表
    vector<int> nums1 = {12, 1, 2, 5, 6, 9};
    node* a = getList(nums1);
    node* c = reverseList(a);
    printList(c);



    return 0;
}
posted @ 2024-04-11 15:26  铜锣湾陈昊男  阅读(6)  评论(0)    收藏  举报