鏈表(list)的實現(c語言)


鏈表是一種基本的數據結構,今天練習了一下,所以將代碼貼在下面,代碼測試通過,代碼還可以優化,我會過段時間就會增加一部分或者優化一部分直達代碼無法優化為止,我的所有數據結構和算法都會用這樣的方式在博客上面更新。

 

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int key;
    struct node *next;
};

typedef struct node Node;

Node *head = NULL;

void insert(int num)
{
    Node * new_node, *current;
    new_node = (Node*)malloc(sizeof(Node));

    new_node->key = num;

    if(head == NULL || head->key > num)
    {
        new_node->next = head;
        head = new_node;
    }
    else
    {
        current = head;
        while(1)
        {
            if(current->next ==NULL || current->next->key > num )
            {
                new_node->next = current->next;
                current->next = new_node;
                break;
            }
            else
            {
                current = current->next;
            }
        }
    }
}

void print()
{
   Node * current;
   if(head == NULL)
   {
       printf("鏈表為空!\n");
   }
   current = head;
   while(current != NULL)
   {
       printf("%d\n",current->key);
       current = current->next;
   }
}

Node * delete(int num)
{
    Node * current = head;
    Node * answer;
    if(head != NULL && head->key == num)
    {
        head = head->next;
        return current;
    }
    else if(head != NULL && head->key > num)
    {
       return NULL;
    }

    while(current != NULL)
    {
        Node * answer;
        if(current->next != NULL && current->next->key == num)
        {
            answer = current->next;
            current->next = current->next->next;
            return answer;
        }else if(current->next != NULL && current->next->key > num)
        {
            return NULL;
        }

        current = current->next;
    }

    return NULL;
}

int main()
{
    Node * x;
    insert(14);
    insert(2);
    insert(545);
    insert(44);
    print();

    x = delete(44);
    if(x != NULL)
    {
        free(x);
    }
    print();


    return 0;
}

 


免責聲明!

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



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