单链表

简介: 单链表

单链表的定义


由于顺序表的插入删除操作需要移动大量的元素,影响了运行效率,因此引入了线性表的链式存储——单链表。单链表通过一组任意的存储单元来存储线性表中的数据元素,不需要使用地址连续的存储单元,因此它不要求在逻辑上相邻的两个元素在物理位置上也相邻。


#include <stdio.h>
#include <stdlib.h>
struct stu{
    int num;
    struct stu* next;
};
//创建一个头结点
struct stu* creat_list(){
    struct stu *headNode=(struct stu*) malloc(sizeof(struct stu));
//    headNode->num=0;
    headNode->next=NULL;
    return headNode;
}
//创建一个结点
struct stu *creat_node(int num){
    struct stu *node=(struct stu*) malloc(sizeof(struct stu));
    node->num=num;
    node->next=NULL;
    return node;
}
//创建一个单链表,头插法
void insert_byHead(struct stu *headNode,int num){
    struct stu* newnode=creat_node(num);
    newnode->next= headNode->next;
    headNode->next=newnode;
}
//尾插法
void insert_tail(struct stu *List,int num){
    while(List->next) List = List->next;
    struct stu *h=List;
    struct stu *newnode= creat_node(num);
    h->next=newnode;
    h=newnode;
    newnode->next=NULL;
}
void printList(struct stu* headNode){
    struct stu *pmove=headNode->next;
    while (pmove){
        printf("%d ",pmove->num);
        pmove=pmove->next;
    }
    printf("\n");
}
void delete(struct stu *list,int num){
    struct stu* pos=list->next;
    struct stu* posfront=list;
    if(posfront->next==NULL){
        printf("the link is empty\n");
    } else{
        while (pos->num!=num){
            posfront=pos;
            pos=pos->next;
        }
        if(pos->next==NULL){
            printf("Not find");
        }
    }
    posfront->next=pos->next;
    free(pos);
}
void main(){
    struct stu *list=creat_list();
    insert_byHead(list,222);
    insert_byHead(list,111);
    insert_byHead(list,555);
    insert_byHead(list,33);
    insert_tail(list,666);
    insert_byHead(list,9);
    insert_tail(list,0);
    printList(list);
//    delete(list,33);
//    printList(list);
}


相关文章
|
7月前
|
存储
【单链表】
【单链表】
37 0
|
2月前
|
存储 C语言
单链表详解
单链表详解
33 0
|
4月前
|
存储 缓存
详解单链表
详解单链表
38 0
详解单链表
|
5月前
单链表的实现
单链表的实现
|
11月前
|
存储
【链表】单链表的实现
【链表】单链表的实现
45 0
|
11月前
|
存储 编译器
【链表之单链表】
什么是链表 概念:链表是一种物理存储结构上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的 。 通俗地讲,就是一个结构体有两个成员,一个是存放数据的成员,一个是指针成员,通常的单链表是第一个节点的指针成员存着下一个节点的地址,下一个节点的指针成员又存下一个节点的地址,这样每个节点之间连接起来,就叫做链表。 本文主要讲的是链表中的一种重要的形式:单链表。
|
存储 Java
单链表
单链表
67 0
单链表
|
存储 API 索引
链表——单链表
单向链表是链表的一种,它由多个结点组成,每个结点都由一个数据域和一个指针域组成,数据域用来存储数据,指针域用来指向其后继结点。链表的头结点的数据域不存储数据,指针域指向第一个真正存储数据的结点。
71 0
链表——单链表