雙向迴圈連結串列(建立·插入·刪除·遍歷)
阿新 • • 發佈:2019-02-16
author:chen ming dong
#include<stdio.h>
#include<stdlib.h>
typedef struct list
{
int a;
struct list *next;
struct list *prior;
}str;
int n;
str * creat(str *head)
{
str *p,*pt;
printf("要輸入幾個資料?\t");
scanf("%d",&n);
int m=n;
printf("\n請輸入\n");
scanf("%d ",&head->a);
p=pt=head;
while(m>1)
{
m--;
p=(str *)malloc(sizeof(str));
scanf("%d",&p->a);
p->prior=pt;
pt->next=p;
pt=p;
}
head->prior=p;
p->next=head;
return head;
}
//遍歷
void gothrough(str *head )
{
str *p;
p=head;
printf("正向遍歷\n");
int m=n;
while(m)
{
m--;
printf("%-3d",p->a);
p=p->next;
}
printf("\n反向遍歷\n");
m=n;
while(m)
{
m--;
p=p->prior;
printf("%-3d",p->a);
}
}
//刪除節點,不是刪除資料
void deletelist(str *head )
{
printf("你要刪除哪個節點?\t");
int node;
scanf("%d",&node);
str *front,*behind;
front=behind=head;
behind=behind->next;
int m=n;
if(node>2)
while(node>2)
{
behind=behind->next;
front=front->next;
node--;
}
if(1==node)
{
head->a=behind->a;// 本來開始不是這樣的,突然發現好像頭結點不能刪除,不然遍歷會出問題 。所以換了一個方法 假刪除頭結點
}
behind=behind->next;
front->next=behind;
behind->prior=front;
head=front;
n--;
}
//插入節點,準確的說我只插入到了尾部,懶得很,今天還有很多事要做 插入中間其實也不難
void insert(str *head)
{
int a,node=n;
str *p,*q,*str1;
str1=(str *)malloc(sizeof(str));
printf("\n你要插入的數\n");
scanf("%d",&str1->a);
p=head;
while(node>1)
{
p=p->next;
node--;
}
q=p->next;
p->next=str1;
str1->prior=p;
q->prior=str1;
str1->next=q;
n++;
}
int main()
{
str *head;
int m;
head=(str *)malloc(sizeof(str));// 重點**為他分配空間是必須的(1.其他函式沒有對她進行分配空間 2.就算其他空間分配了空間也只能在那個函式中有效,我們要的是全域性有效)
head=creat(head);
gothrough(head);
while(1)
{
printf("\n1.新增資料\t2.刪除資料\t3.正反遍歷\n");
scanf("%d",&m);
if(1==m)
{
insert(head);
}
if(2==m)
{
deletelist(head);
}
if(3==m)
{
gothrough(head);
}
}
}
程式碼剛寫的,希望有大牛們給點意見或建議