老规矩直接淦代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct dolinklist {
int data;
struct dolinklist* prior;
struct dolinklist* next;
}node;
node* Creatlist() {//头节点创建
node* head = (node*)malloc(sizeof(node));
assert(head);
head->next = head->prior = NULL;
return head;
}
void Initlist(node* head,int num) {
if (head->next != NULL) {
node* tmp = head;
while (tmp->next) {
tmp = tmp->next;
}
node* p = (node*)malloc(sizeof(node));
p->data = num;
p->next = NULL;
p->prior = tmp;
tmp->next = p;
}
else {
node* p = (node*)malloc(sizeof(node));
p->data = num;
p->next = NULL;
p->prior = head;
head->next = p;
}
}
void display(node* head) {//双向链表的打印
if (head->next != NULL) {
node* tmp = head;
while (tmp->next) {
tmp = tmp->next;
printf("%d ", tmp->data);
}
printf("\n");
}
else {
printf("no num");
}
}
node* Delet(node* head, int num) {
node* p;
p = head;
if (p->next == NULL) {
printf("无元素删除\n");
}
else {
p = p->next;
//printf("%d\n", p->data);
for (p; p && (p->data - num); p = p->next);
if (p->next == NULL) {
p->prior->next = NULL;
free(p);
}
else {
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
}
}
return head;
}
node* Insert(node* head, int num) {//头插一个节点
node* p = head;
node* t = (node*)malloc(sizeof(node));
p = p->next;
t->data = num;
t->next = p;
t->prior = p->prior;
p->prior->next = t;
p->prior = t;
return head;
}
int main() {
node* head = Creatlist();
node* p;
int n = 0;
int arr[1024] = { 0 };
int deletnum = 0;
int Insertnum = 0;
//输入链表元素
printf("请输入要插入的元素个数:\n");
scanf("%d", &n);
printf("请输入元素:\n");
for (int i = 0; i < n; i++) {
(void)scanf("%d", &arr[i]);
Initlist(head, arr[i]);
}
//打印;链表元素
display(head);
//删除链表元素
printf("请输入要删除的元素:\n");
scanf("%d", &deletnum);
node* hn=Delet(head,deletnum);
display(hn);
//增添链表元素(头插)
printf("请输入要增加的数字:\n");
scanf("%d", &Insertnum);
node* hn1=Insert(hn, Insertnum);
display(hn);
return 0;
}
其他插还没学会.......
|