头文件:
#pragma once
#include <windows.h>
#include <iostream>
using namespace std;
typedef struct _tagNode
{
int data;
_tagNode *next;
}Node,*pNode;
//创建列表
pNode CreateNode(int size);
//删除列表
BOOL DeleteNode(pNode pHead);
//显示列表
void ShowNode(pNode pHead);
//插入节点
pNode InsertNode(pNode pHead, pNode pNewNode,int index);
//添加节点在最后添加
pNode AddNode(pNode pHead, pNode pNewNode);
//删除节点
pNode RemoveNode(pNode pHead, int index);
源文件:
#include "stdafx.h"
#include "MyNode.h"
pNode CreateNode(int size)
{
cout<<"当前操作:创建节点。。。。。。。"<<endl;
pNode pHead = new Node();
pHead->next = NULL;
pNode pLast = pHead;
if(pHead == NULL)
{
cout<<"err create node head"<<endl;
}
int input;
for(int i=0; i<size; i++)
{
pNode tmp = new Node();
if(tmp == NULL)
{
cout<<"创建链表节点失败!"<<endl;
}
cout<<"请输入链表的第"<<i<<"个元素:";
cin>>input;
tmp->data = input;
tmp->next = NULL;
//让头结点的next只想新元素
pLast->next = tmp;
//让尾节点指向新元素
pLast = tmp;
}
return pHead;
}
BOOL DeleteNode(pNode pHead)
{
cout<<"当前操作:清空列表。。。。。。。"<<endl;
cout<<"删除元素开始:"<<endl;
pNode p=pHead;
while(pHead!=NULL)
{
p = pHead;
cout<<"当前头指向的节点:"<<pHead<<"\t";
cout<<"当前马上要删除的节点p:"<<p<<"\t";
pHead = pHead->next;
cout<<"下一个节点为:"<<pHead<<endl;
delete p;
}
return TRUE;
}
void ShowNode(pNode pHead)
{
cout<<"当前操作:显示列表。。。。。。。"<<endl;
//设置个节点指针指向当前元素
pNode p = pHead;
while(p->next!=NULL)
{
//因为头结点没有元素,所以写在显示的前面
p = p->next;
cout<<"元素:"<<p->data<<endl;
}
}
pNode InsertNode(pNode pHead, pNode pNewNode,int index)
{
cout<<"当前操作:在某个位置插入节点。。。。。。。"<<endl;
pNode p = pHead;
//查找到索引
int iFind = 1;
while(TRUE)
{
p = p->next;
iFind++;
if(iFind==index)
{
cout<<"当前需要插入的地方是:"<<iFind<<endl;
break;
}
}
pNewNode->next = p->next;
p->next = pNewNode;
return pHead;
}
pNode AddNode(pNode pHead, pNode pNewNode)
{
cout<<"当前操作:在最后添加节点。。。。。。。"<<endl;
//先申请个临时节点,用于保存最后节点的位置
pNode p = pHead;
//查找节点,因为最后一个节点的next为null
while(p->next != NULL)
{
p = p->next;
}
//添加数据
p->next = pNewNode;
return pHead;
}
pNode RemoveNode(pNode pHead, int index)
{
cout<<"当前操作:删除某个位置上的节点。。。。。。。"<<endl;
//查找某个元素的前面那个元素
pNode p = pHead;
int iFind = 0;
while(TRUE)
{
if(iFind == index-1)
{
break;
}
p = p->next;
iFind++;
}
//删除元素
pNode tmp = p->next;
p->next = p->next->next;
delete tmp;
return pHead;
}