c語言 雙向鏈表的簡單操作-創建、插入、刪除


數據結構-雙向鏈表的創建、插入和刪除

雙向鏈表是數據結構中重要的結構,也是線性結構中常用的數據結構,雙向指針,方便用戶從首結點開始沿指針鏈向后依次遍歷每一個結點,結點的前驅和后繼查找方便。

#include <stdio.h>

#include <stdlib.h>

//雙向鏈表結點的定義

typedef struct dbnode

{

int data;

struct dbnode *prio, *next;

}DbNode, linkdblist;

 

//創建雙向鏈表

DbNode *creatlist(void)

{

linkdblist *p, *q, *head;

q = p = (linkdblist *)malloc(sizeof(linkdblist));

p->next = NULL;

head = q;

p = (linkdblist *)malloc(sizeof(linkdblist));

scanf("%d", &p->data);

while (p->data != -1)

{

q->next = p;

p->prio = q;

q = p;

p = (linkdblist *)malloc(sizeof(linkdblist));

scanf("%d", &p->data);

}

q->next = NULL;

return head;

}

 

//輸出雙向鏈表

void print(linkdblist *head)

{

linkdblist *p;

p = head->next;

if (p == NULL)

printf("空鏈表!\n");

while (p != NULL)

{

printf("%d  ", p->data);

p = p->next;

}

}

 

//向雙向鏈表中的第i個位置插入一個結點x

void insertdblist(linkdblist *head, int x, int i)

{

linkdblist *p, *q = head;

if (i == 1)

q = head;

else

{

q = q->next;

int c = 1;

while ((c<i - 1) && (q != NULL))

{

q = q->next;

c++;

}

}

if (q != NULL && q->next != NULL)

{

p = (linkdblist *)malloc(sizeof(linkdblist));

p->data = x;

p->prio = q;

p->next = q->next;

q->next = p;

q->next->prio = p;

}

else

printf("找不到插入的位置!");

}

 

//刪除雙向鏈表中指定位置上的一個結點

void deletelinkdblist(linkdblist *head, int i)

{

linkdblist *p, *q = head;

if (i == 1)

q = head;

else

{

q = q->next;

int c = 1;

while (c < i - 1 && q != NULL)

{

q = q->next;

c++;

}

}

if (q != NULL && q->next != NULL)

{

p = q->next;

p->prio = q;

p->prio->next = p->next;

p->next->prio = p->prio;

free(p);

}

else if (q->next == NULL)

{

p = q;

p->prio->next = NULL;

free(p);

}

else

printf("沒有找到待刪除的結點");

}

//雙向鏈表的主函數

void main()

{

linkdblist *head;

head = creatlist();

print(head);

 

printf("\n\n====向雙向鏈表的某位置插入一個值====\n");

int num, i;

printf("輸入插入的位置:");

scanf("%d", &i);

printf("\n輸入插入的值:");

scanf("%d", &num);

insertdblist(head, num, i);

print(head);

printf("\n");

 

printf("\n\n====刪除雙向鏈表的某位置上的一個值====\n");

int j;

printf("輸入刪除的位置:");

scanf("%d", &j);

deletelinkdblist(head, j);

print(head);

system("pause");

printf("\n");

 

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM