C/C++实现双向链表及基本操作

接下来,我要用一段C/C++代码实现双向链表的构建,插入,删除操作。这是链表操作中比较基本的操作,我是模仿单向链表来进行双向链表的构建,其插入和删除操作也和单向链表大同小异,代码并不晦涩难懂,适合新手研读,有错误或者不够完善的希望大家指出。

#include "pch.h"
#include 
#include 
#include 
using namespace std;

/* 构建双向链表(3指针法 模仿单链表创建 */
typedef struct NODE
{
	int data;           //结点数据
	NODE *pNext;        //指向直接前驱
	NODE *Prior;        //指向直接后继
	int pos;            //结点位置
}Node;

Node* create_List()
{
	//三指针法创建双向链表,类似单链表的创建
	Node *head, *p1, *p2;
	head = p1 = p2 = new Node;
    head->Prior = NULL;   //头结点的前指针置空
	cin >> head->data;
	head->pos = 1;        //结点位置  
    for (int i = 2; i <= 6; i++) //这里创建一个5结点双向链表
	{
		p1 = new Node;
		cout << "...Please input the data: ";
		cin >> p1->data;
		p1->pos = i;     //结点位置
		p1->Prior = p2;
		p2->pNext = p1;
		p2 = p1;
	}
	    p1->pNext = NULL;
	    return head;
    }

void showLIST(Node* head)   //双向链表的遍历
{
	Node *p = head;
	while (p)
	{
		if (p->pNext == NULL)
		{
			cout << p->data;
		}
        else
		{
			cout << p->data;
			Sleep(800);
			cout << " <-> ";
		}
		    p = p->pNext;
	} 
	cout << endl;
}

//随机插入
Node* insert(Node* head)
{
	Node* p = head;
	Node *temp;
	Node *insert_Node = new Node;
	int i;
    cout << "...你想插在哪一个结点上: ";
	cin >> i;
	cout << "...好的,你想插入的结点数据是: ";
	cin >> insert_Node->data;
    if (i == 1)        //插入在第一个结点
	{
		insert_Node->Prior = NULL;
		insert_Node->pNext = head;
		head->Prior = insert_Node;

		head = insert_Node;
	}
	else               //插入在其他结点
	{
		while (p)
		{
			temp = p;  //暂时保存当前结点
			p = p->pNext;
            if (p->pos == i && p!=NULL)   //对应某一位置的结点
			{
				insert_Node->pNext = p;
				insert_Node->Prior = temp;
				temp->pNext = insert_Node;
            }
                p->Prior = insert_Node;
				break;    //一旦找到插入位置 记得跳出循环 不要浪费时间和内存
			}			
		}
	}
	return head;
}

//随机删除
Node* delet(Node* head)
{
	Node *p = head;
	Node *temp;
	short data;
	cout << "...你想删除的结点数据是: ";
	cin >> data;
    if (head->data == data)      //如果是第一个结点
	{
		temp = head->pNext;
		head->pNext->Prior = NULL;
		delete head;
		head = NULL;
		head = temp;
	}
    else    //如果不是第一个结点
	{
		while (p)
		{
			temp = p;    //暂时保存当前结点
			p = p->pNext;
			
            if (p->pNext == NULL && p->data ==data)  //如果是最后一个结点
			{
				temp->pNext = NULL;
				delete p;
				p = NULL;
			}
			else       //如果不是最后一个结点
			{
				if (p->data == data)
				{
					temp->pNext = p->pNext;
					p->pNext->Prior = temp;
					delete p;
					p = NULL;
				}
			}
		}
	}
	return head;
}
     
    int main(){
	cout << "...Please input the data: ";
	Node *p = create_List();
	showLIST(p);
	cout << endl << endl;   
	
	/*插入*/	
	Node *p1 = insert(p);
	cout << endl << "...插入后进行遍历 " << endl;
	Sleep(1000);
	showLIST(p1);

    /* 删除 */
	Node *p2 = delet(p);
	cout << endl << "...删除后进行遍历 " << endl;
	showLIST(p2);
	cout << endl << endl;
	
    delete p1, p2;
	system("pause");
	return 0;
}

实现效果如下
C/C++实现双向链表及基本操作_第1张图片

你可能感兴趣的:(C/C++,数据结构,链表,链表,数据结构,c语言)