数据结构 单链表 附代码

什么是链表?

链表是结构体变量与结构体变量通过指针连接在一起。
创建静态链表:

include <stdio.h>
struct Node{
    int data;
    struct Node * next;
};
int main(){
    struct Node Node1={1,null};
    struct Node Node2={2,null};
    struct Node Node3={1,null};
    Node1.next=&Node2;
    Node2.next=&Node3;
return 0;
}

动态创建一个链表:动态内存申请+模块化设计
1、创建链表(创建一个表头表示整个链表)
2、创建节点
3、插入结点
4、删除节点
5、打印遍历链表(测试)
1、创建动态链表

struct Node{
    int data;
    struct Node *next;
};
struct Node* createList()
{
    struct Node* headNode=(struct Node*)(malloc(sizeof(struct Node)));
    //headNode成为了结构体变量,变量使用前必须初始化
    //headNode->data=1;
    headNode->next=NULL;
}

2、创建结点

//创建结点
struct Node *createNode(int data)
{
    struct Node* newNode=(struct Node*)(malloc(sizeof(struct Node)));
    newNode->data=data;
    newNode->next=NULL;
    return newNode;
}

3、插入节点(头插法)

//插入结点,参数:插入哪个链表,插入节点的数据是多少
void insertNodeByHead(struct Node* headNode,int data)
{
    struct Node* newNode=createNode(data);
    newNode->next=headNode->next;
    headNode->next=newNode;
}

4、删除节点

//删除节点
void deleteNodeByAppoin(struct Node* headNode,int posData)
{
   struct Node* posNode=headNode->next;
   struct Node* posNodeFront=headNode;
   if(posNode==NULL)
        printf("链表为空,无法删除\n");
   else
   {
       while(posNode->data!=posData)
       {
           posNodeFront=posNode;
           posNode=posNodeFront->next;
          if(posNode==NULL){
                printf("没有找到相关信息,无法删除!\n");
                return;
           }
       }
       posNodeFront->next=posNode->next;
       free(posNode);
   }
}

5、打印节点

//打印链表
void printList(struct Node* headNode)
{
    struct Node* pMove;
    while(pMove){
        printf("%d",pMove->data);
        pMove=pMove->next;
    }
    printf("\n");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值