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

// 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
", 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;
}
原文地址:https://www.cnblogs.com/wumac/p/4763450.html