链表的基本操作-双向链表

来源:互联网 发布:csgo武器数据 编辑:程序博客网 时间:2024/06/12 01:33

微笑微笑

双向链表一般也由头指针唯一确定
双向链表首尾相接可以构成双向循环链表 

微笑

/*链表的基本操作~~开发环境:vs2010win32 console application.*/#include "stdafx.h"#include <iostream>using namespace std;struct node{int data;node * next;  // 指向后续节点node * pre;   // 指向前驱节点};node * createBidirList (int n);void outputBidirList(node * head);node * insertData(int n, node * head);node * deleteData(int n, node * head);int main() {    int n;node * listHead = NULL;cout << "Please enter the number of nodes: ";cin >> n;  // 可以输入5 (1 2 3 4 5)if(n > 0)listHead = createBidirList(n);outputBidirList(listHead);insertData(7, listHead);outputBidirList(listHead);insertData(6, listHead);deleteData(2, listHead);outputBidirList(listHead);return 0;}


//  按数据输入的顺序建立双向链表 node * createBidirList (int n) {node * temp, *tail = NULL, *head = NULL;int num;cin >> num;head = new node; //为新节点动态分配内存if(head == NULL) {cout << "No memory available!";return NULL;}else  {head->data = num;head->next = NULL;head->pre = NULL;tail = head;}for(int i = 0; i < n - 1; i++) {cin >> num;temp = new node;  //为新节点动态分配内存if(temp == NULL) {cout << "No memory availabe";return head;}else {temp->data = num;temp->next = NULL;temp->pre = tail;tail->next = temp;tail = temp;}}return head;}

 

 

// 输出双向链表中各节点的data成员的值 void outputBidirList(node * head) {cout << "List: ";node * curNode = head;while(curNode) {if(curNode->pre)cout << " <- ";cout << curNode->data;if(curNode->next)cout << " -> ";curNode = curNode->next;}cout << endl;return;}


// 将整数n插入到一个已排序的双向链表中(从小到大)node * insertData(int n, node * head) {node * curNode = head;  // 指向插入点的后节点node * preNode = NULL;  // 指向插入点的前节点node * newNode = NULL;  // 指向新建节点// 寻找插入位置while((curNode != NULL) && (curNode->data < n)) {preNode = curNode;curNode = curNode->next;}newNode = new node;  // 为新节点动态分配内存if(newNode == NULL) { // 内存分配不成功cout << "Not memory available!";return head;}newNode->data = n;if(preNode == NULL) { // 链头newNode->next = curNode;newNode->pre = NULL;if(curNode != NULL)curNode->pre = newNode;head = newNode; return head;}if(curNode == NULL) {  // 链尾newNode->pre = preNode;preNode->next = newNode;newNode->next = NULL;return head;}else{ // 链中preNode->next = newNode;newNode->next = curNode;newNode->pre = preNode;curNode->pre = newNode;return head;}}
// 在双向链表中查找并删除指定node * deleteData(int n, node * head) { node * curNode = head; // 指向当前节点 while(curNode && curNode->data != n) curNode = curNode->next; if(curNode == NULL) { cout << "Can't find " << n << endl; return head; } if(curNode->pre == NULL) { head = head->next; head->pre = NULL; } else { curNode->pre->next = curNode->next; if(curNode->next != NULL) curNode->next->pre = curNode->pre; } delete curNode; return head; // 返回链首指针}


 

 

 

 

原创粉丝点击