您的位置:首页 > 编程语言 > C语言/C++

如何编写自己单向链表(c语言)

2012-10-16 23:42 531 查看
最近由于项目需要用到链表,所以就研究了研究,之前吧见是见多了,也看得懂。可是到自己真正用起来,自己写出一个链表还真给我郁闷了好几天!现在终于有点眉目了,写一篇文章来记录一下,以便后面查阅只用。

其实一个链表不难,写一个链表主要有几个重要步骤,

1,构建结构,一个简单单向链表结构应包括两个域的:数据域和指针域,数据域当然就是我们所关心的内容啦,指针域就是为了构建链表用的,即指向下一个结构的首地址。

2,定义表头,即一个指向该链表的首节点的指针;

3,添加节点,往一个链表添加一个节点,这是相当重要的一步,我们之所以要用动态链表就是为了节省空间,在用到的时候动态的申请一块内存,然后将其添加到链表里面;当然用动态链表不光是为了节省空间。还有很多优点,其实我也不知道有哪些优点.................就略过了!这里最关键的也就是首先要找到尾节点而将其加入。

废话少说,上一个示例性的代码

编译环境 Redhat9 gcc

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//list.h

#ifndef LIST_H

#define LIST_H

#include<stdio.h>

#include"typedef.h"

typedef struct siglelist_t

{

struct siglelist *next;

uint8 num;

uint8 scope;

}siglelist; //链表结构

extern siglelist *head;//

//申明函数

uint8 list_add_node(uint8 num,uint8 scope);

void print_list(void);

#endif

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

list.c

#include<stdio.h>

#include"typedef.h"

#include"list.h"

siglelist *head;//定义头指针

uint8 list_add_node(uint8 num,uint8 scope)

{

siglelist *pList;

siglelist *pLast;

siglelist *pNew;

pList = pLast = head;

while(pList)

{

if(pList->num == num&& pList->scope ==scope)

return 1;

pLast = pList;

pList = (siglelist *)pList ->next;

}

pNew = (siglelist *)malloc(sizeof(siglelist));

if(pNew)

{

pNew ->num = num;

pNew ->scope=scope;

pNew ->next =NULL;

if(head)

{

pLast->next = pNew;

}

else

{

head = pNew;

}

return 1;

}

else

return 0;

}

//打印节点数据

void print_list(void)

{

siglelist *p;

p= head;

printf("now print the list node info\n");

while(p != NULL)

{

printf("%d,%d\n",p->num,p->scope);

p = p->next;

}

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

main.c

#include<stdio.h>

#include"list.h"

#include"typedef.h"

int main(void)

{

uint8 i;

siglelist *p;

p = malloc(sizeof(siglelist));

while(1)

{

printf("please input node data\n");

scanf("%d,%d",&p->num,&p->scope);

printf("num:%d,scope:%d\n",p->num,p->scope);

list_add_node(p->num,p->scope);

print_list();

}

}

很简单吧!运行结果: 休息了苦逼的程序猿!!!1明天还要7点赶公交!!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: