关于链表

在笔试题中经常会遇到关于链表的操作,对于我这种没有系统学过数据结构的人
来说每次写完,总会感觉有地方写的不对,所以我就完完整整地将关于链表的函数
在这来写一遍,希望再遇到这种题目的时候能手到擒来。
以下代码包含是链表的创建,插入,遍历函数。
虽然没有注释,但都在我电脑上编译通过,并且可以正常运行的。

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

#define ERROR 0
#define OK 1

//定义链表节点
typedef struct Node{
    int data;
    struct Node *next;
}Node, *pNode; 

//创建一个空链表 
int CreatList(pNode *pHead){
    *pHead = (pNode)malloc(sizeof(Node));
    (*pHead) -> next = NULL;
    if(NULL == pHead)
        return ERROR;
    return OK;  
} 

//在链表的末尾插入一个节点,节点元素为e 
int ListInsert_end(pNode *pHead, int e){
    pNode p,s;
    s = (pNode)malloc(sizeof(Node));
    if(NULL == s)
        return ERROR;
    p = (*pHead);
    while(p->next)
        p = p -> next;    
    s -> data = e;
    s -> next = NULL;
    p -> next = s;


    return OK; 
} 

//在链表的第i个节点前插入一个节点,节点元素为e 
int ListInsert(pNode *pHead, int i, int e){
    pNode p, s;
    s = (pNode)malloc(sizeof(Node));
    if(NULL == s)
        return ERROR;
    p = *pHead ;
    while( p->next && --i){
        p = p -> next;
    }
    if(i)
         return ERROR;
    s -> data = e;
    s -> next = p -> next;
    p -> next = s;

    return OK;   
} 
//遍历一个链表
int ListPrint(pNode *pHead){
    pNode p;
    p = *pHead;
    if(p->next == NULL)
    {
        printf("这是一个空表\n");
        return OK;
    } 
    while(p->next){
        p = p -> next;
        printf("%d ",p -> data);
    }
    printf("\n");
    return OK;
}


int main(){
    pNode Lc;
    CreatList(&Lc);
    ListInsert_end(&Lc, 1);
    ListInsert_end(&Lc, 2);
    ListInsert_end(&Lc, 3);
    ListPrint(&Lc);
    ListInsert(&Lc,2,44); 
    ListPrint(&Lc);
    ListInsert(&Lc,4,45); 
    ListPrint(&Lc);
}

就这么一点代码,耗费了我好几个小时,不过收获自知,也就够了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值