//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;
}
双向链表(Doubly Linked List) (ACM学习笔记)
最新推荐文章于 2022-09-26 22:15:58 发布