1. 程式人生 > >【資料結構】線性表的鏈式儲存連結串列的初始化、插入元素、刪除元素操作(三)

【資料結構】線性表的鏈式儲存連結串列的初始化、插入元素、刪除元素操作(三)

雙向連結串列的初始化插入與刪除

程式碼收穫

  • 雙向連結串列刪除結點需要注意要刪除最後一個結點和不是最後一個結點分類討論。
  • 插入和刪除時注意修改上一個結點裡指向下一個結點的指標與下一個結點裡指向上一個結點的指標。
#include <stdio.h>
#include <stdlib.h>
//雙向連結串列,一個結構裡除了資料外有2個指標,一個指向前一個節點,一個指向後一個節點
typedef struct biprolist{
	struct biprolist *head;
	char data;
	struct biprolist *tail;
}Node,*Nodep; 
//初始化連結串列,有一個頭結點,讓其head和tail指向null
void InitialList(Nodep *L){
	*L = (Nodep)malloc(sizeof(Node));
	(*L)->head = NULL;
	(*L)->tail = NULL; 
} 
//頭插法 
void InsertList(Nodep L){
	printf("請輸入插入的資料,$結束\n");
	int flag = 1;
	while(flag){
		char c;
		c = getchar();
		if(c!='$'){
			Nodep newnode;
			newnode = (Nodep)malloc(sizeof(Node));
			newnode->data=c;
			newnode->head=L;
			newnode->tail=L->tail;
			L->tail = newnode;
			if(newnode->tail!=NULL)
			{newnode->tail->head = newnode;}
		}else{
			flag=0;
		}
	}
	getchar();//吃回車 
} 
//尾插法
void Inserttail(Nodep L){
	printf("請輸入要插入的資料,$結束\n");
	int flag = 1;
	Nodep movep;//找到讓其始終指向尾巴
	movep=L;
	while(movep->tail!=NULL){
		movep = movep->tail;
	}
	while(flag){
		char c;
		c = getchar();
		if(c!='$'){
			Nodep newnode;
			newnode=(Nodep)malloc(sizeof(Node));
			newnode->data=c;
			newnode->head=movep;
			newnode->tail=NULL;
			movep->tail=newnode;
			movep = newnode; 
		}else{
			flag=0;
		}
	}
	getchar();
} 

void Printlist(Nodep L){
	Nodep move;
	move = L;
	printf("連結串列為\n");
	while(move->tail!=NULL){
		move=move->tail;
		printf("%c",move->data);
	}
	printf("\n倒著為\n");
	while(move->head!=NULL){
		printf("%c",move->data);
		move= move->head;
	}
	
}
//刪除節點
int DeleteNode(Nodep L){
	int flag =1;
	while(flag){
		int num;
		Nodep move=L;
		printf("請輸入要刪除的節點索引(從0開始)\n");
		scanf("%d",&num);
		int i;
		for(i=0;i<=num;i++){
			if(move->tail==NULL){
				printf("索引錯誤\n");
				return 1;
			}else{move=move->tail;
			}
		}if(move->tail==NULL){
			move->head->tail=NULL;
			free(move);
		}else{
		move->head->tail =move->tail;
		move->tail->head = move->head;
		free(move);}
		Printlist(L);
		printf("是否繼續(y/n)\n");
		getchar();
		char f;
		f= getchar();
		if(f=='n'){
			flag = 0;
		}
	} return 0;
} 
void main(){
	Nodep L;
	InitialList(&L);
	InsertList(L);
	Printlist(L);
	Inserttail(L);
	Printlist(L);
	DeleteNode(L);
}