您的位置:首页 > 其它

单链表的插入和遍历 包括头插入和尾插入

2015-08-27 15:27 381 查看
// Win32Project1.cpp : 定义控制台应用程序的入口点。
//
//单链表的插入和遍历
#include "stdafx.h"
#include <AccCtrl.h>

typedef struct sNode
{
int data;
struct sNode * pNext;
}Node,* pNode;
pNode gHead = NULL;
void add(int d);//尾部插入节点
void addHead(int d);//头部插入节点
void print();//遍历打印
int _tmain(int argc, _TCHAR* argv[])
{
add(88);
addHead(77);
add(99);
print();

getchar();
return 0;
}
void add(int d)
{
pNode p = gHead;
pNode pNew = (pNode)malloc(sizeof(Node));
pNew->data = d;
pNew->pNext = NULL;
if (!p)
{
gHead = pNew;
return;
}
while (p->pNext)
{
p = p->pNext;
}
p->pNext = pNew;
return;
}
void print()
{
while (gHead)
{
printf("%d\n", gHead->data);
gHead = gHead->pNext;
}
}
void addHead(int d)
{
pNode p = gHead;
pNode pNew = (pNode)malloc(sizeof(Node));
pNew->data = d;
pNew->pNext = gHead->pNext;
p = pNew;
gHead->pNext = pNew;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: