/************************************************************************/
/* @author lynnbest
雙向迴圈列表的使用:
1.建立
2.插入
3.刪除
4.列印
5.按位置查詢
6.按內容查詢
7.退出 */
/************************************************************************/
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *prior;
struct node *next;
}Dlistnode;
Dlistnode *CreateDClist(int n);
void printflist(Dlistnode *head);
int lengthlist(Dlistnode *head);
void InsertDClist(Dlistnode *head,int pos);
void DeleteDClist(Dlistnode *head,int pos);
void main()
{
printf(" 雙向迴圈連結串列基本操作 \n");
printf("----by lynnbest ----\n\n");
int choice,num;
Dlistnode *head;
while(1)
{
printf("1---建立一個雙向迴圈連結串列\n");
printf("2---插入節點操作\n");
printf("3---刪除節點操作\n");
printf("4---列印連結串列元素\n");
printf("5---查詢操作(按位置)\n");
printf("6---查詢操作(按內容)\n");
printf("7---退出\n請輸入操作:\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("請輸入建立元素的個數:\n");
scanf("%d",&num);
head=CreateDClist(num);
break;
case 2:
printf("輸入插入的位置:\n");
scanf("%d",&num);
InsertDClist(head,num);
break;
case 3:
printf("輸入刪除的位置:\n");
scanf("%d",&num);
DeleteDClist(head,num);
break;
case 4:
printflist(head);
// printf("共有%d個元素\n",lengthlist(head));
break;
case 5:
break;
case 6:
break;
case 7:
return ;
break;
default :
break;
}
}
}
Dlistnode *CreateDClist(int n) //建立一個帶頭節點的雙向迴圈連結串列
{
Dlistnode *head,*newnode,*pre;
int data;
if(NULL==(head=(Dlistnode *)malloc(sizeof(Dlistnode))))
{
printf("頭結點建立失敗\n");
exit(-1);
}
pre=head;
for(int i=1;i<=n;i++)
{
if(NULL==(newnode=(Dlistnode *)malloc(sizeof(Dlistnode))))
{
printf("建立失敗\n");
exit(-1);
}
printf("請輸入第%d個元素\n",i);
scanf("%d",&data);
newnode->data=data;
//開始插入
pre->next=newnode;
newnode->prior=pre;
pre=newnode;
newnode->next=NULL;
}
newnode->next=head;
head->prior=newnode; //做首位迴圈
return head;
}
void printflist(Dlistnode *head)
{
Dlistnode *cur=head->next;
while(cur->next!=head)
{
printf("%3d",cur->data);
cur=cur->next;
}
printf("%3d\n",cur->data);
return ;
}
int lengthlist(Dlistnode *head)
{
Dlistnode *cur=head;
int count=0;
while(cur->next!=head)
{
count++;
cur=cur->next;
}
return count;
}
void InsertDClist(Dlistnode *head,int pos)
{
if(pos<1||pos>lengthlist(head)+1){
printf("插入位置非法\n");
return ;
}
Dlistnode *cur=head,*newnode;
int data;
//完成插入點資料建立
if(NULL==(newnode=(Dlistnode *)malloc(sizeof(Dlistnode))))
{
printf("建立失敗\n");
exit(-1);
}
printf("請輸入要插入的節點資料:\n");
scanf("%d",&data);
newnode->data=data;
for(int i=0;i<pos;i++) //查詢要插入的位置
cur=cur->next;
//開始插入
cur->prior->next=newnode; //插入需要4步
newnode->prior=cur->prior;
newnode->next=cur;
cur->prior=newnode;
}
void DeleteDClist(Dlistnode *head,int pos)
{
if(pos<1||pos>lengthlist(head)){
printf("刪除位置非法\n");
return ;
}
Dlistnode *cur=head;
for(int i=0;i<pos;i++) //查詢要刪除節點的位置
cur=cur->next;
//刪除 需要3步
cur->prior->next=cur->next; //前一個指標指向刪除節點的下一個
cur->next->prior=cur->prior;//刪除節點的前驅指標 指向刪除節點前一個節點
free(cur);//釋放堆
}