Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux C 數據結構——線性表與單鏈表的完整實現

線性表的存儲結構分為順序存儲與鏈式存儲兩類。順序存儲的優點是支持隨機訪問、時間開銷小;缺點是插入刪除需要大量搬移元素,且容量必須預先確定,擴展不便。

鏈表正是鏈式存儲的典型代表:它把線性表 L = (a0, a1, a2, …, an-1) 中各元素分散存放在存儲器的不同塊中,每塊稱為結點(Node),通過地址或指針建立彼此之間的聯繫,得到的存儲結構就是鏈表。表中元素 ai 的結點形式如下:

Linux C 數據結構——線性表與單鏈表的完整實現

其中 data 域存放數據元素 ai,next 域是指針,指向 ai 的直接後繼 a(i+1) 所在的結點。

一、結點類型描述

typedef struct node_t
{
    data_t data;            //結點的數據域
    struct node_t *next;    //結點的後繼指針域
}linknode_t, *linklist_t;

也可以拆開寫:

struct node_t
{
    data_t data;
    struct node_t *next;
};
typedef struct node_t linknode_t;
typedef struct node_t *linklist_t;

若定義:

linknode_t A;
linklist_t p = &A;

則結構變量 A 就是一個節點,指針變量 p 是指向該類型節點的指針(p 的值是節點地址)。

這樣看來 linknode_t 與 linklist_t 好像沒什麼區別,那為什麼要定義兩個名字?主要是為了代碼可讀性——標識符要望文生義:

1)linknode_t *pnode 一眼看出指向某個節點;
2)linklist_t list 一眼看出指向整個鏈表。

二、頭結點 head

前面講順序存儲時,空表 { } 是用 list->last = -1 來表達的,本質是數據域為空。而鏈表有數據域和指針域,怎麼表達空鏈表呢?這裡就引入了頭結點的概念:頭結點的類型與其他節點完全相同,只是不存數據,令 head->next = NULL 即為空表。

linklist_t CreateEmptyLinklist()
{
    linklist_t list;
    list = (linklist_t)malloc(sizeof(linknode_t));
    if (NULL != list) {
        list->next = NULL;
    }
    return list;
}

只要頭結點還在,鏈表就還在——這也是頭結點最大的好處:插入、刪除首元素時不必再特殊判斷「是不是第一個節點」。

三、鏈表基本運算

除了創建空表,鏈表還有插入、刪除、查找、求長度、反轉等操作。寫這類函數時,如何兼顧效率與封裝性是要認真權衡的。以插入為例,就至少要考慮:1)目標鏈表是空表;2)插入位置超出了鏈表長度。函數若能覆蓋所有可能情況,不僅開發效率提高,出錯率也會顯著下降。

int InsertLinklist(linklist_t list, int at, data_t x)
{
    linknode_t *node_prev, *node_at, *node_new;
    int pos_at;
    int found = 0;
    if (NULL == list) return -1;
    /* at must >= 0 */
    if (at < 0) return -1;
    /* 第一步、分配空間 */
    node_new = malloc(sizeof(linknode_t));
    if (NULL == node_new)
    {
        return -1;
    }
    node_new->data = x;
    node_new->next = NULL;
    /* 第二步、定位 */
    node_prev = list;       //跟隨指針
    node_at = list->next;   //遍歷指針
    pos_at = 0;
    while (NULL != node_at)
    {
        if (pos_at == at)
        {
            found = 1;      //找到正確位置,跳出循環
            break;
        }
        node_prev = node_at;    //跟隨指針跟到遍歷指針原位
        node_at = node_at->next;//遍歷指針前進
        pos_at++;
    }
    /* 第三步、插入 */
    if (found)
    {
        node_new->next = node_at;   //新節點 next 指向 node_at
        node_prev->next = node_new; //前驅接上新節點
    }
    else
    {
        /* 沒找到即插入位置超出表長,接到尾節點後面;
           這種處理同樣適用於空表,於是可以用它完成鏈表初始化 */
        node_prev->next = node_new;
    }
    return 0;
}

這個插入函數的適用面就很廣。下面是完整的鏈表實現,分為頭文件與源文件兩部分。

listlink.h:

#ifndef _LNK_LIST_H_
#define _LNK_LIST_H_
typedef int data_t;
typedef struct node_t {
    data_t data;
    struct node_t *next;
} linknode_t, *linklist_t;

linklist_t CreateEmptyLinklist();
void DestroyLinklist(linklist_t list);
void ClearLinklist(linklist_t list);
int EmptyLinklist(linklist_t list);
int LengthLinklist(linklist_t list);
int GetLinklist(linklist_t list, int at, data_t *x);
int SetLinklist(linklist_t list, int at, data_t x);
int InsertLinklist(linklist_t list, int at, data_t x);
int DeleteLinklist(linklist_t list, int at);
linklist_t ReverseLinklist(linklist_t list);
#endif /* _LNK_LIST_H_ */

linklist.c:

#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"

linklist_t CreateEmptyLinklist()
{
    linklist_t list;
    list = (linklist_t)malloc(sizeof(linknode_t));
    if (NULL != list) {
        list->next = NULL;
    }
    return list;
}

void DestroyLinklist(linklist_t list)
{
    if (NULL != list) {
        ClearLinklist(list);
        free(list);
    }
}

void ClearLinklist(linklist_t list)
{
    linknode_t *node;   /* 待刪除的節點 */
    if (NULL == list) return;
    while (NULL != list->next) {
        node = list->next;
        list->next = node->next;
        free(node);
    }
    return;
}

int LengthLinklist(linklist_t list)
{
    int len = 0;
    linknode_t *node;
    if (NULL == list) return -1;
    node = list->next;      // node 指向第一個數據節點
    while (NULL != node) {
        len++;
        node = node->next;
    }
    return len;
}

int EmptyLinklist(linklist_t list)
{
    if (NULL != list) {
        if (NULL == list->next) {
            return 1;
        } else {
            return 0;
        }
    } else {
        return -1;
    }
}

int GetLinklist(linklist_t list, int at, data_t *x)
{
    linknode_t *node;
    int pos;
    if (NULL == list) return -1;
    if (at < 0) return -1;
    node = list->next;
    pos = 0;
    while (NULL != node) {
        if (at == pos) {
            if (NULL != x) {
                *x = node->data;
            }
            return 0;
        }
        node = node->next;
        pos++;
    }
    return -1;
}

int SetLinklist(linklist_t list, int at, data_t x)
{
    linknode_t *node;
    int pos;
    int found = 0;
    if (!list) return -1;
    if (at < 0) return -1;
    node = list->next;
    pos = 0;
    while (NULL != node) {
        if (at == pos) {
            found = 1;
            node->data = x;
            break;
        }
        node = node->next;
        pos++;
    }
    if (1 == found) {
        return 0;
    } else {
        return -1;
    }
}

int DeleteLinklist(linklist_t list, int at)
{
    linknode_t *node_prev, *node_at;
    int pos_at;
    int found = 0;
    if (!list) return -1;
    if (at < 0) return -1;
    node_prev = list;
    node_at = list->next;
    pos_at = 0;
    while (NULL != node_at) {
        if (pos_at == at) {
            found = 1;
            break;
        }
        node_prev = node_at;
        node_at = node_at->next;
        pos_at++;
    }
    if (found) {
        node_prev->next = node_at->next;
        free(node_at);
        return 0;
    } else {
        return -1;
    }
}

linklist_t ReverseLinklist(linklist_t list)
{
    linknode_t *node;       /* 遍歷指針 */
    linknode_t *node_prev;  /* 遍歷指針的前驅 */
    linknode_t *node_next;  /* 備份 node 的後繼 */
    if (NULL == list) return NULL;
    node_prev = NULL;
    node = list->next;
    while (NULL != node) {
        /* step1: 先備份 node->next,因為下一步會修改它 */
        node_next = node->next;
        /* 當遍歷到原鏈表最後一個節點時,讓頭結點指向它 */
        if (NULL == node_next) {
            list->next = node;
        }
        /* step2: 反轉指向,讓 node 指向前驅而非後繼 */
        node->next = node_prev;
        /* step3: 全體前進 */
        node_prev = node;
        node = node_next;
    }
    return list;
}

main.c:

#include <stdio.h>
#include <stdlib.h>
#include "linklist.h"

int main()
{
    int i;
    data_t x;
    linklist_t p;
    p = CreateEmptyLinklist();
    data_t a[10] = {1,3,5,7,9,11,13,15,17,19};
    for (i = 0; i < 10; i++)
    {
        InsertLinklist(p, i, a[i]);
    }
    ReverseLinklist(p);
    printf("The length of the list is:%d\n", LengthLinklist(p));
    GetLinklist(p, 4, &x);
    printf("The NO.4 of this list is:%d\n", x);
    SetLinklist(p, 4, 100);
    GetLinklist(p, 4, &x);
    printf("After updating! The No.4 of this list is:%d\n", x);
    DeleteLinklist(p, 4);
    printf("After updating! The length of the list is:%d\n", LengthLinklist(p));
    GetLinklist(p, 4, &x);
    printf("After updating! The No.4 of this list is:%d\n", x);
    ReverseLinklist(p);
    ClearLinklist(p);
    if (EmptyLinklist(p))
        printf("This list is empty!\n");
    DestroyLinklist(p);
    printf("This list is destroyed!\n");
    return 0;
}

執行結果:

fs@ubuntu:~/qiang/list/list2$ ./Test
The length of the list is:10
The NO.4 of this list is:11
After updating! The No.4 of this list is:100
After updating! The length of the list is:9
After updating! The No.4 of this list is:9
This list is empty!
This list is destroyed!

反轉函數是整份代碼裡最值得反覆琢磨的一段:關鍵在於先用 node_next 存好後繼,再改寫 node->next,最後整體前移,三步順序一旦顛倒,鏈表就會斷成兩截。

Copyright © Linux教程網 All Rights Reserved