双向链表(Doubly Linked List) (ACM学习笔记)

//Doubly Linked List

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>

using namespace std;

struct node {
    int date;
    struct node* next;
    struct node* pre;
};

struct node* Creat_list(int n) {
    int i;
    struct node* head, * tail, * p;
    head = new struct node;
    head->next = NULL;
    head->pre = NULL;//make Head_List_Node
    tail = head;
    for (i = 0; i < n; i++) {
        p = new struct node;
        scanf("%d", &p->date);
        p->next = NULL;
        p->pre = NULL;
        tail->next = p;
        p->pre = tail;
        tail = p;
    }
    return head;
};

struct node* Delete(struct node* head, int key) {
    struct node* p;
    p = head->next;//head->data = NULL
    while (p) {
        if (p->date == key) {
            p->pre->next = p->next;
            if (p->next) p->next->pre = p->pre;
        }
        p = p->next;
    }
    return head;
}

struct node* Insert(struct node* head, int pos, int key) {
    struct node* p;
    p = head->next;
    struct node* q;
    q = new struct node;
    q->date = key;  q->next = NULL;  q->pre = NULL; //Make New_Node
    int cnt = 0;
    if (pos == 0) { // Insert -> List_Head_Node
        if (head->next) {
            head->next->pre = q;  q->next = head->next;
            head->next = q;       q->pre = head;
        }
        else {
            head->next = q;  q->pre = head;
        }
    }
    else {
        while (p) {
            cnt++;
            if (cnt == pos) break;
            p = p->next;
        }
        if (p->next) {
            p->next->pre = q; q->next = p->next;
            p->next = q;  q->pre = p;
        }
        else { // Insert -> List_Tail_Node
            p->next = q;  q->pre = p;
        }
    }
    return head;
}

int main() {
    struct node* head, * p;
    int n;
    scanf("%d", &n);
    head = Creat_list(n); //创建双向链表
    p = head->next;
    while (p) {
        printf("%d\t", p->date);
        p = p->next;
    }
    printf("\n\n");

    struct node* head2; //存储删除某个元素后的链表
    int key;
    scanf("%d", &key);
    head2 = Delete(head, key);
    p = head2->next;
    while (p) {
        printf("%d\t", p->date);
        p = p->next;
    }
    printf("\n\n");

    struct node* head3; //存储添加某个元素后的链表
    int pos;
    scanf("%d %d", &pos, &key);
    head3 = Insert(head2, pos, key);
    p = head3->next;
    while (p) {
        printf("%d\t", p->date);
        p = p->next;
    }
    printf("\n");

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值