天天看點

【c語言】連結清單(完整版)

c語言之連結清單(完整版)

      • 連結清單(完整版)
全國新增确診連續兩天為0
喜迎遍地飄零的時刻
海外遊子也在回家
一起加油!
           

連結清單(完整版)

此版包括以下功能:

連結清單建立、

頭插、

尾插、

删除、

翻轉、

删除相同元素、

周遊、

判斷連結清單是否為空

以下為源碼

若有不嚴謹的地方,歡迎指正

//連結清單建立、頭插、尾插、删除、翻轉、删除相同元素、周遊、判斷連結清單是否為空
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
    int data;
    struct Node *next;
}Node;
int main(){
    //主函數中不能指定一個頭指針,應該定義一個頭指針指向頭結點
    Node *head = (Node*)malloc(sizeof(Node));
    head -> next = NULL;
    createLink(head,10);//建立連結清單
    travelLink(head);//周遊連結清單
    insertForward(head,100);//頭插法
    insertBack(head,200);//尾插法
    travelLink(head);//周遊連結清單
    deleteSame(head);//删除相同元素
    travelLink(head);//周遊連結清單
    reverseLink(head);//翻轉連結清單元素
    travelLink(head);//周遊連結清單
    deleteLink(head);//删除連結清單
    isEmpty(head);//判斷連結清單是否為空
    return 0;
}
//建立連結清單
void createLink(Node *head,int size){
    Node *rear = head;
    int i;
    for(i = 0;i < size;++i){
        Node *newnode = (Node*)malloc(sizeof(Node));
        newnode -> next = NULL;
        scanf("%d",&newnode->data);
        rear -> next = newnode;
        rear = newnode;
    }
}
//周遊連結清單
void travelLink(Node *head){
    Node *p = head -> next;
    while(p != NULL){
        printf("%d\t",p->data);
        p = p -> next;
    }
    putchar('\n');
}
//頭插法
void insertForward(Node *head,int data){
    Node *newnode = (Node*)malloc(sizeof(Node));
    newnode -> next = NULL;
    newnode -> data = data;
    newnode -> next = head -> next;
    head -> next = newnode;
}
//尾插法
void insertBack(Node *head,int data){
    Node *newnode = (Node*)malloc(sizeof(Node));
    newnode -> next = NULL;
    newnode -> data = data;
    Node *p = head;
    while(p->next != NULL){
        p = p -> next;
    }
    p -> next = newnode;
    p = newnode;
}
//删除相同元素
void deleteSame(Node *head){
    Node *curr = head -> next;
    while(curr != NULL){
        Node *pre = curr;
        Node *p = curr -> next;
        while(p != NULL){
            //若有相同的元素,則删除;否則兩個指針繼續向下走
            if(curr->data == p->data){
                pre -> next = p -> next;
                free(p);
                p = pre -> next;
            }else{
                pre = pre -> next;
                p = p -> next;
            }
        }
        curr = curr -> next;
    }
}
//翻轉連結清單
void reverseLink(Node *head){
    Node *curr;
    Node *pre = NULL;
    while(head -> next != NULL){
        curr = head -> next;
        head -> next = curr -> next;
        curr -> next = pre;
        pre = curr;
    }
    head -> next = pre;
}
//删除連結清單
void deleteLink(Node *head){
    Node *curr;
    while(head -> next != NULL){
        curr = head -> next;
        head -> next = curr -> next;
        free(curr);
    }
}
//判斷連結清單是否為空
void isEmpty(Node *head){
    if(head -> next == NULL){
        printf("連結清單為空!\n");
    }else{
        printf("連結清單不為空!\n");
    }
}

           

運作結果

【c語言】連結清單(完整版)

繼續閱讀