实现双向链表:创建、插入、删除
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> using namespace std; typedef struct student { int data; struct student *next; struct student *pre; }dnode; //创建链表 dnode *create() { //1. 定义变量 dnode *head = NULL; dnode *p = NULL; dnode *s = NULL; int x = 0; int cycle = 1; //2. 新建head head = (dnode*)malloc(sizeof(dnode)); p = head; //3. 添加节点 while(cycle) { printf("input the data:"); scanf("%d", &x); if (x != 0) { s = (dnode*)malloc(sizeof(dnode)); s->data = x; p->next = s; s->pre = p; p = s; } else { cycle = 0; } } //4. 删除 head p->next = NULL; p = head; head = head->next; free(p); p = NULL; //5. 返回 head return head; } //插入节点 dnode *insert(dnode *head, int num) { //1. 定义变量 dnode *p0 = NULL; dnode *p1 = NULL; p1 = head; //2. 新建节点 p0 = (dnode*)malloc(sizeof(dnode)); p0->data = num; //3. 定位插入位置(升序) while(p0->data > p1->data && p1->next != NULL) { p1 = p1->next; } //4. 插入新节点 if (p0->data > p1->data) //尾 { p1->next = p0; p0->pre = p1; p0->next = NULL; } else { if (head == p1) //头 { p0->next = p1; p1->pre = p0; head = p0; } else //中间 { p1->pre->next = p0; p0->next = p1; p0->pre = p1->pre; p1->pre = p0; } } //5. 返回 head return head; } //删除节点 dnode *del(dnode *head, int num) { //1. 定义变量 dnode *p = NULL; p = head; //2. 定位节点 while (num != p->data && p->next != NULL) { p = p->next; } //3. 删除节点 if (num != p->data) { printf("not found:%d ", num); } else { if (p == head) //头 { head = p->next; head->pre = NULL; free(p); } else if (p->next == NULL) //尾 { p->pre->next = NULL; free(p); } else //中间 { p->next->pre = p->pre; p->pre->next = p->next; free (p); } } return head; } //计算链表长度 int length(dnode *head) { dnode *p; int n = 0; p = head; while(p != NULL) { p = p->next; n++; } printf("len:%d ", n); return n; } //显示 void show(dnode *head) { dnode *p; int n = 0; p = head; while(p != NULL) { printf("data:%d ", p->data); p = p->next; } printf(" "); } int main() { dnode *head = create(); show(head); length(head); head = insert(head, 2); show(head); head = del(head, 2); show(head); }