首页 > 编程语言 > 详细

C语言实现单链表

时间:2020-10-27 18:33:56      阅读:35      评论:0      收藏:0      [点我收藏+]
链表是一种物理存储单元上非连续、非顺序的存储结构数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。 相比于线性表顺序结构,操作复杂。由于不必须按顺序存储,链表在插入的时候可以达到O(1)的复杂度,比另一种线性表顺序表快得多,但是查找一个节点或者访问特定编号的节点则需要O(n)的时间,而线性表和顺序表相应的时间复杂度分别是O(logn)和O(1)。
使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。链表最明显的好处就是,常规数组排列关联项目的方式可能不同于这些数据项目在记忆体磁盘上顺序,数据的存取往往要在不同的排列顺序中转换。链表允许插入和移除表上任意位置上的节点,但是不允许随机存取。链表有很多种不同的类型:单向链表双向链表以及循环链表。链表可以在多种编程语言中实现。像Lisp和Scheme这样的语言的内建数据类型中就包含了链表的存取和操作。程序语言或面向对象语言,如C,C++和Java依靠易变工具来生成链表。
#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
    int data;
    struct  Node *next;
} node;

//创建一个头节点
node * create_list(int x){
    node *p=(node *)malloc(sizeof(node));
    p->data=x;
    p->next=NULL;      
    return p;
}

//链表添加节点
void add_list(node *head,int x){
    if(!head)return;
    while (head->next)  
    {
        head=head->next; //当指针不为空时,表明不是最后的节点,向后移动
    }
    node *p=(node *)malloc(sizeof(node));  //创建一个新的节点
    p->data=x;
    p->next=NULL;
    head->next=p;  //关联链表


}
//查找节点
node * find_list(node *head,int x){
    while (head&&head->data!=x)
    {
        head=head->next;   //如果不是最后的节点或节点的值不相等,则指针后移
    }
    if (head)
        return head;
    return NULL;
}
//打印链表的值
void print_list(node *head){
    while (head)
    {
        printf("%d->",head->data);
        head=head->next;
    }
    printf("null\n");
}

//向链表中插入值为n的元素
node * insert_list(node *head,int n,int i){
    int j=0;
    while (head&&j<i-1)
    {
        head=head->next;
        j++;
    }
    if (!head)
    {
          return NULL;      
    }
    node *p=(node *)malloc(sizeof(node));  //创建一个新的节点
    p->data=n;
    p->next=head->next;
    head->next=p;
    return p;
}

//删除根据索引位置删除链表的位置
void  delete_list(node *head,int i){
    int j=0;
    while (head&&j<i-1)
    {
        head=head->next;
        j++;
    }
    //head->next=head->next->next;
    node *p=(node *)malloc(sizeof(node)); 
    p=head->next;
    head->next=p->next;
    free(p);
}
//获取链表中的某一元素
node * get_elem(node *head,int i){
    int j=0;
    while (head&&j<i-1)
    {
        head=head->next;
        j++;
    }
    if (j!=i-1)
    {
       return NULL;
    }
    printf("%d->",head->data);
    return head;
}

void main(){
    node *head =create_list(1);
    add_list(head,5);
    add_list(head,3);
    add_list(head,7);
    add_list(head,8);
    print_list(head);
    insert_list(head,9,2);
    delete_list(head,2);
    get_elem(head,2);
    
}
 

 

C语言实现单链表

原文:https://www.cnblogs.com/HTLucky/p/13885350.html

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