双链表的创建、测长、打印、插入和删除
2014-04-03 16:23
246 查看
内容RT,实现代码如下所示:
1.头结点插入和删除
2.中间结点插入和删除
3.尾结点插入和删除
#include <iostream> #include <stdio.h> #include <string> using namespace std; typedef struct student { int data; struct student *next; struct student *pre; }dnode; // 建立双链表 dnode *creat() { dnode *head, *p, *s; int x, cycle = 1; head = new dnode; p = head; while (cycle) { cout << "Please input data for dnode : "; cin >> x; if (x != 0) { s = new dnode; s->data = x; cout << x << endl; p->next = s; s->pre = p; p = s; } else { cycle = 0; } } head = head->next; head->pre = NULL; p->next = NULL; //cout << "Head data of dnode is " << head->data << endl; return head; } //链表插入 dnode *Insert(dnode *head, int num) { dnode *p0, *p1; p0 = new dnode; p0->data = num; p1 = head; while (p0->data > p1->data && p1->next != NULL) { p1 = p1->next; } if (p0->data <= p1->data) { if (p1 == head)// 头节点插入 { p0->next = p1; p1->pre = p0; head = p0; } else//中间结点插入 { p1->pre->next = p0; p0->next = p1; p0->pre = p1->pre; // 遗忘点 p1->pre = p0; } } else// 尾部插入结点 { p1->next = p0; p0->pre = p1; p0->next = NULL; } return head; } // 双链表删除 dnode *del(dnode *head, int num) { dnode *p1; p1 = head; while (num != p1->data && p1->next != NULL) { p1 = p1->next; } if (p1->data == num) { if (p1 == head)//首结点 head head->next { head = head->next; head->pre = NULL; delete p1; } else { if (p1->next == NULL)// 尾节点 p1->pre p1 NULL { p1->pre->next = NULL; delete p1; } else//中间结点 { p1->next->pre = p1->pre; p1->pre->next = p1->next; delete p1; } } } else { cout << "Please check out the data !" << endl; } return head; } // 打印双链表 void PrintDL(dnode *head) { dnode *p = head; int l = 0; while (p != NULL) { p = p->next; l++; } cout << "The length of dnode is " << l << endl; p = head; for (int i = 0; i < l; i++) { cout << "The dnode data is " << p->data << endl; p = p->next; } } int main() { cout << "****创建双链表****" << endl; dnode *head = creat(); cout << endl; cout << "****双链表测长和打印****" << endl; PrintDL(head); cout << endl; cout << "***双链表插入数据***" << endl; cout << "Please input the int data for ins operate : "; int Indata1 = 0; cin >> Indata1; head = Insert(head, Indata1); PrintDL(head); cout << endl; cout << "***双链表删除数据***" << endl; cout << "Please input the int data for del operate : "; int Indata2 = 0; cin >> Indata2; head = del(head, Indata2); PrintDL(head); cout << endl; return 0; }
1.头结点插入和删除
2.中间结点插入和删除
3.尾结点插入和删除
相关文章推荐
- [C/C++]反转链表
- 关于指针的一些事情
- C/C++数据对齐详细解析
- C++中引用的使用总结
- C与C++之间相互调用实例方法讲解
- C++中引用(&)的用法与应用实例分析
- 解析C++ 浮点数的格式化输出
- 深入分析C++中几个最不常用的关键字
- c++中inline的用法分析
- C++ Primer 第一部分基本语言
- 深入解析C++ Data Member内存布局
- 从汇编看c++中默认构造函数的使用分析
- 关于C++中的友元函数的一些总结
- C++的sstream标准库详细介绍
- 基于C++自动化编译工具的使用详解
- 浅谈C++中的string 类型占几个字节
- C/C++ 宏详细解析
- 深入分析C++中两个大数相乘结果不正确的问题
- 探讨C++中数组名与指针的用法比较分析
- 深入解析C++中的引用类型