单链表

Posted on 2018-05-18 23:10  ben_zhuback  阅读(124)  评论(0)    收藏  举报

#include<iostream>
#include<stdio.h>

using namespace std;

typedef struct node
{
int nValue;
struct node *pNext;
}List;

void Push(List** pphead,List** ppend,int num)
{
List* pNode = (List*)malloc(sizeof(List));
pNode->pNext = NULL;
pNode->nValue = num;


//头添加
//if(*pphead == NULL)
//{
// *pphead = pNode;
// *ppend = pNode;
//}
//else
//{
// pNode->pNext = *pphead;
// *pphead = pNode;
// *ppend = *pphead;
//}

//尾添加
if(*pphead == NULL)
{
*pphead = pNode;
}
else
{
(*ppend)->pNext = pNode;
}
*ppend = pNode;
}

void Traveral(List* phead)
{
while(phead)
{
cout<<phead->nValue<<" ";
phead = phead->pNext;
}
cout<<"\n";
}


List* FindNode(List* phead,int num)
{
while(phead)
{
if(phead->nValue == num)
return phead;
phead =phead->pNext;
}
return NULL;
}
void Pop(List** pphead,List** ppend,int num)
{
if(*pphead == NULL) return;
List* pPreDel = *pphead;
List* pDel = *pphead;

//头删除
if(pDel->nValue == num)
{
*pphead = (*pphead)->pNext;
if(*pphead == NULL) //只有一个节点的情况
*ppend = NULL;
free(pDel);
pDel = NULL;
return;
}

while(pPreDel->pNext)
{
if(pPreDel->pNext->nValue == num)
{
pDel = pPreDel->pNext;
pPreDel->pNext = pDel->pNext;

//尾删除
if(pDel == *ppend)
{
*ppend = pPreDel;
}
free(pDel);
pDel = NULL;
return;
}
pPreDel = pPreDel->pNext;
}

cout<<"没有找到要删除的节点"<<endl;

}

void Insert(List* phead,List**ppend,int index,int num) //第几个结点后面插入 也可以通过数字找特定的节点后面插入
{
List* pNode = (List*)malloc(sizeof(List));
pNode->pNext = NULL;
pNode->nValue = num;

while(--index)
phead = phead->pNext;
pNode->pNext = phead->pNext;
phead->pNext = pNode;

if(phead == *ppend)
*ppend = pNode;

}

int main()
{
List* phead = NULL;
List* pend = NULL;
for(int i = 0 ;i<5;i++)
{
Push(&phead,&pend,i);
}
Traveral(phead);
Pop(&phead,&pend,0);
Traveral(phead);
Insert(phead,&pend,4,20);
Traveral(phead);
Push(&phead,&pend,100);
Traveral(phead);
return 0;
}