码迷,mamicode.com
首页 > 其他好文 > 详细

单链表(带头节点)

时间:2019-11-30 16:28:16      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:eof   memset   链表   length   节点   new   null   sys   判断   

/////////////////////////////////定义节点结构体

struct node
{
int data;
struct node *pnext;
};

 

////////////////////////////////////main函数

int main()
{

struct node *pHeader = creatList(0);

/*insert_tail(creatList(1),pHeader);
insert_tail(creatList(2),pHeader);
insert_tail(creatList(3),pHeader);*/

insert_head(creatList(1),pHeader);
insert_head(creatList(2),pHeader);
//creatList(1);
printf("p1的data为:%d 总的节点数为:%d\n",pHeader->pnext->data,pHeader->data);
printf("p2的data为:%d 总的节点数为:%d\n",pHeader->pnext->pnext->data,pHeader->data);
//printf("p3的data为:%d 总的节点数为:%d\n",pHeader->pnext->pnext->pnext->data,pHeader->data);
//creatList(2);
system("pause");
return 0;
}

//////////////////////////////////创建新节点

struct node * creatList(int data)
{
struct node *p ;
p =(struct node *)malloc(sizeof(struct node));
//忘记判断了
if(p == NULL)
{
printf("创建节点指针失败");
return NULL;
}
//忘记清0了
memset(p,0,sizeof(struct node));
p->data = data;
p->pnext = NULL;
return p;
}

///////////////////////////////尾插法

void insert_tail(struct node * newNode, struct node *pHeader)
{
struct node * p = pHeader;
int length = 0;
while(p->pnext!= NULL)
{
p = p->pnext;
length++;
}
pHeader->data = length+1;
p->pnext = newNode;

}

//////////////////////////////////////头插法

void insert_head(struct node *newNode,struct node *pheader)
{
struct node * p = newNode;
p->pnext = pheader->pnext;
pheader->pnext = p;

pheader->data +=1;
}

单链表(带头节点)

标签:eof   memset   链表   length   节点   new   null   sys   判断   

原文地址:https://www.cnblogs.com/tiange-137/p/11962938.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!