链表操作

#include <iostream>
using namespace std;


struct node
{
    int data;
    struct node *next;
};
void insert_list(node **head, int i)
{
    node *p = *head;
    node *pre = p;
    while (p != NULL) {
        pre = p;
        p = p->next;
    }
    node* node_inst = new node();
    node_inst->data = i;
    node_inst->next = NULL;
    if (*head == NULL) {
        *head = node_inst;
    } else {
        pre->next = node_inst;
    }
}
void delete_list(node **head, int num)
{
    if (*head == NULL) return;
    node *pre = *head;
    node *cur = *head;
    node *next = (*head)->next;
    if (cur->data == num) {
        delete cur;
        cur = NULL;
        *head = cur = next;
        return;
    }
    while (next != NULL) {
        if (next->data == num) {
            pre->next = next->next;
            delete next;
            next = NULL;
            return;
        } else {
            pre = next;
            next = next->next;
        }
    }
}
void revert_list(node **head)
{
    if (*head == NULL) return;
    node *pre = NULL;
    node *cur = *head;
    node *next = (*head)->next;
    while (next != NULL) {
        cur->next = pre;
        pre = cur;
        cur = next;
        next = next->next;
    }
    cur->next = pre;
    *head = cur;
}
node * merge_list(node *head1, node *head2)
{
    if (head1 == NULL) return head2;
    if (head2 == NULL) return head1;
    node *new_head = NULL;
    if (head1->data < head2->data) {
        new_head = head1;
        new_head->next = merge_list(head1->next, head2);
    } else {
        new_head = head2;
        new_head->next = merge_list(head1, head2->next);
    }
    return new_head;
}
int main()
{
    node *head1 = NULL;
    for (int i = 0; i < 10; i += 2) {
        insert_list(&head1, i);
    }
    node *p = head1;
    while (p != NULL) {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
    delete_list(&head1, 4);
    p = head1;
    while (p != NULL) {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
    //revert_list(&head1);
    //p = head1;
    //while (p != NULL) {
    //    cout << p->data << " ";
    //    p = p->next;
    //}
    //cout << endl;
    node *head2 = NULL;
    for (int i = 1; i < 10; i += 2) {
        insert_list(&head2, i);
    }
    p = head2;
    while (p != NULL) {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
    p = merge_list(head1, head2);
    while (p != NULL) {
        cout << p->data << " ";
        p = p->next;
    }
    cout << endl;
    getchar();
    return 0;
}

 

转载于:https://www.cnblogs.com/kaishan1990/p/6270695.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值