1. 程式人生 > 實用技巧 >【15】連結串列基本操作(c語言程式碼)

【15】連結串列基本操作(c語言程式碼)

單鏈表

雙鏈表

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

// 雙向連結串列
typedef struct DoubleNode
{
        int data;
        struct DoubleNode * pre, * next;
}Node;

void PrintList(Node * head)
{
        Node * cur = head->next;
        while(cur != head) {
                printf(" %d  ", cur->data);
                cur 
= cur->next; } printf("\n"); } int LenList(Node * head) { Node * cur = head->next; int n; while(cur != head) { cur = cur->next; n++; } return n; } // 建立連結串列 Node * CreateList() { Node * head = (Node*) malloc (sizeof
(Node)); if (NULL == head) exit(-1); head->next = head; head->pre = head; return head; } // void InsertList(Node * head, int data) { Node * cur = (Node*) malloc (sizeof(Node)); if (NULL == cur) exit(-1); cur->data = data; cur
->next = head->next; head->next = cur; // cur->pre = head; 可以 // cur->pre->next = cur; 不可以 cur->pre = head->pre; cur->next->pre = cur; } // void DeleteList1(Node * head, int data) { Node * cur = head->next; while(cur != head) { if (cur->data == data) { cur->pre->next = cur->next; cur->next->pre = cur->pre; free(cur); } cur = cur->next; } } // 銷燬 void DestoryList(Node * head) { head->pre->next = NULL; Node * cur; while(head) { cur = head; head = head->next; free(cur); } } int main() { printf("建立連結串列:\n"); Node * head = CreateList(); PrintList(head); printf("插入連結串列:\n"); int i; for(i=0; i<100; i+=10) { InsertList(head, i); } PrintList(head); printf("刪除連結串列:\n"); DeleteList(head, 40); PrintList(head); DestoryList(head);