單鏈表的基本操作


原文 http://c.biancheng.net/view/3338.html

 

 

 

#include <stdio.h>
#include <stdlib.h>
typedef struct Link {
    int  elem;
    struct Link *next;
}link;
link * initLink();
//鏈表插入的函數,p是鏈表,elem是插入的結點的數據域,add是插入的位置
link * insertElem(link * p, int elem, int add);
//刪除結點的函數,p代表操作鏈表,add代表刪除節點的位置
link * delElem(link * p, int add);
//查找結點的函數,elem為目標結點的數據域的值
int selectElem(link * p, int elem);
//更新結點的函數,newElem為新的數據域的值
link *amendElem(link * p, int add, int newElem);
void display(link *p);
int main() {
    //初始化鏈表(1,2,3,4)
    printf("初始化鏈表為:\n");
    link *p = initLink();
    display(p);
    printf("在第4的位置插入元素5:\n");
    p = insertElem(p, 5, 4);
    display(p);
    printf("刪除元素3:\n");
    p = delElem(p, 3);
    display(p);
    printf("查找元素2的位置為:\n");
    int address = selectElem(p, 2);
    if (address == -1) {
        printf("沒有該元素");
    }
    else {
        printf("元素2的位置為:%d\n", address);
    }
    printf("更改第3的位置上的數據為7:\n");
    p = amendElem(p, 3, 7);
    display(p);
    return 0;
}
link * initLink() {
    link * p = (link*)malloc(sizeof(link));//創建一個頭結點
    link * temp = p;//聲明一個指針指向頭結點,用於遍歷鏈表
    //生成鏈表
    for (int i = 1; i < 5; i++) {
        link *a = (link*)malloc(sizeof(link));
        a->elem = i;
        a->next = NULL;
        temp->next = a;
        temp = temp->next;
    }
    return p;
}
link * insertElem(link * p, int elem, int add) {
    link * temp = p;//創建臨時結點temp
    //首先找到要插入位置的上一個結點
    for (int i = 1; i < add; i++) {
        temp = temp->next;
        if (temp == NULL) {
            printf("插入位置無效\n");
            return p;
        }
    }
    //創建插入結點c
    link * c = (link*)malloc(sizeof(link));
    c->elem = elem;
    //向鏈表中插入結點
    c->next = temp->next;
    temp->next = c;
    return  p;
}
link * delElem(link * p, int add) {
    link * temp = p;
    //遍歷到被刪除結點的上一個結點
    for (int i = 1; i < add; i++) {
        temp = temp->next;
        if (temp->next == NULL) {
            printf("沒有該結點\n");
            return p;
        }
    }
    link * del = temp->next;//單獨設置一個指針指向被刪除結點,以防丟失
    temp->next = temp->next->next;//刪除某個結點的方法就是更改前一個結點的指針域
    free(del);//手動釋放該結點,防止內存泄漏
    return p;
}
int selectElem(link * p, int elem) {
    link * t = p;
    int i = 1;
    while (t->next) {
        t = t->next;
        if (t->elem == elem) {
            return i;
        }
        i++;
    }
    return -1;
}
link *amendElem(link * p, int add, int newElem) {
    link * temp = p;
    temp = temp->next;//tamp指向首元結點
    //temp指向被更改結點
    for (int i = 1; i < add; i++) {
        temp = temp->next;
    }
    temp->elem = newElem;
    return p;
}
void display(link *p) {
    link* temp = p;//將temp指針重新指向頭結點
    //只要temp指針指向的結點的next不是Null,就執行輸出語句。
    while (temp->next) {
        temp = temp->next;
        printf("%d ", temp->elem);
    }
    printf("\n");
}

 


免責聲明!

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



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