1. 程式人生 > 實用技巧 >7.5_連結串列_連結串列中新增結點

7.5_連結串列_連結串列中新增結點

在一個有序(非遞減)連結串列中插入新結點,使得新連結串列仍然有序。

#include <stdio.h>
#include <stdlib.h>
//在一個有序(非遞減)連結串列中插入新結點,使得新連結串列仍然有序

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

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

struct linkNode *creat_link_list_rear(int *a, int
n); //尾插法 struct linkNode *insert_sort(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 = insert_sort(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 *insert_sort(struct linkNode *h, int x){ struct linkNode *s; //待插入結點 struct linkNode *p; //遊標 struct linkNode *pre; //前驅 s = (struct linkNode *)malloc(sizeof(struct linkNode)); s->data = x; s->next = NULL; if (h == NULL){ //情況1. h為空連結串列 h = s; } if (x <= h->data){ //情況2. x不大於連結串列中的第一個節點的資料域,將s插在鏈首 s->next = h; h = s; }else{ //情況3. 遊標p指向頭結點 p = h; while (p && x > p->data){ pre = p; p = p->next; } s->next = pre->next; pre->next = s; } return h; //返回連結串列頭結點 } //列印連結串列資料 void output(struct linkNode *head){ struct linkNode *p = head; while (p){ printf("%d ", p->data); p = p->next; } printf("\n"); }