1. 程式人生 > 實用技巧 >7.5_連結串列_刪除指定資料域的結點

7.5_連結串列_刪除指定資料域的結點

將連結串列中值為x的結點刪除。

#include <stdio.h>
#include <stdlib.h>
//將連結串列中值為x的結點刪除

//結點
struct linkNode{
    int data;
    struct linkNode *next;
};

void output(struct linkNode *head);                         //列印連結串列資料域

struct linkNode *creat_link_list_rear(int *a, int n);       //尾插法

struct linkNode *delete_node(struct
linkNode *h, int x); //刪除指定值的結點 int main() { int a[6]; //存放結點資料 int x; //待刪除資料 struct linkNode *head; //頭指標(尾插法) printf("輸入陣列各元素的值【6個】:\n"); for(int i=0; i<6; i++){ scanf("%d", &a[i]); } head = creat_link_list_rear(a, 6); //
尾插法 printf("此連結串列各個節點的資料為:\n"); output(head); printf("輸入要刪除的資料:\n"); scanf("%d", &x); head = delete_node(head, x); printf("\n插入新資料後,此連結串列各個節點的資料為:\n"); output(head); return 0; } //尾插法 struct linkNode *creat_link_list_rear(int a[], int n){ struct linkNode *h = NULL; //
新建連結串列h,將每個結點依次插入到鏈尾,將連結串列的頭指標返回 struct linkNode *s; //要插入的結點 struct linkNode *r; //尾結點 for(int i=0; i<n; i++){ s = (struct linkNode *)malloc(sizeof(struct linkNode)); s->data = a[i]; s->next = NULL; if(h == NULL){ h = s; }else{ r->next = s; } r = s; //r指向當前連結串列的尾結點 } return h; //返回連結串列頭指標 } //刪除指定值的結點 struct linkNode *delete_node(struct linkNode *h, int x){ struct linkNode *p; //遊標 struct linkNode *pre; //p的前驅 p = h; while (p && x != p->data){ pre = p; p = p->next; } if (p){ //p非空(找到了要刪除的結點) if (p == h){ //刪除節點在鏈首 h = p->next; }else{ //刪除節點在鏈中 pre->next = p->next; } } return h; } //列印連結串列資料 void output(struct linkNode *head){ struct linkNode *p = head; while (p){ printf("%d ", p->data); p = p->next; } printf("\n"); }