首页 > 编程语言 > 详细

【15】链表基本操作(c语言代码)

时间:2020-09-09 11:11:59      阅读:61      评论:0      收藏:0      [点我收藏+]

单链表

双链表

#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);

 

【15】链表基本操作(c语言代码)

原文:https://www.cnblogs.com/oytt/p/13637399.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!