//雙鏈表
#include<iostream>
#include<string>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef struct student
{
int data;
struct student *next;
struct student *prior;
}node;
node *creatlist()
{
node *head, *p, *q;
int x;
head = (node*)malloc(sizeof(node));
head->next = NULL;
head->prior = NULL;
//p = head->next; 頭插入法要用的;
p = head;
cout << "請輸入數據,以ctrl+z表示結束" << endl;
//這是頭插入法;
/*while (cin >> x)
{
q = (node*)malloc(sizeof(node));
q->data = x;
q->prior = head;
q->next = p;
head->next = q;
p = q;
}*/
//這是尾插入法;輸出順序和頭插入不一樣;
while (cin >> x)
{
q = (node*)malloc(sizeof(node));
q->data = x;
q->next = p->next;
q->prior = p;
p->next = q;
p = q;
}
return(head);
}
void printlist(node *head)
{
node *p;
p = head->next;
cout << "當前雙鏈表數據爲:" << endl;
while (p != NULL)
{
cout << p->data << endl;
p = p->next;
}
}
//插入;
void insert(node *r, int x)
{
node *p;
p = (node*)malloc(sizeof(node));
p->data = x;
p->next = r->next;
p->prior = r;
r->next->prior = p;
r->next = p;
}
//刪除;
void deletelist(node *head, int x)
{
node *p, *q;
q = head;
p = head->next;
while (p != NULL && p->data != x)
{
q = p;
p = p->next;
}
if (p == NULL)
cout << "該鏈表沒有這個數值" << endl;
else {
q->next = p->next;
p->next->prior = q;
free(p);
}
}
int main()
{
node *head;
head = creatlist();
insert(head, 88);
deletelist(head, 5);
printlist(head);
system("pause");
return 0;
}
雙鏈表的建立以及插入,刪除操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.