以下程序的单链表不含有头结点,其中的头指针指向一个数据结点。
对于链表的操作不要死记 每次可以画个链表示意图,想想操作会不会影响头指针,有没有什么特殊情况
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<ctime>
using namespace std;
typedef struct ListNode
{
int data;
ListNode * next;
}ListNode;
//插入结点考虑两种情况,链表为空链表非空
void AddNodeToTail(ListNode **pHead,int value)//尾插法实现单链的插入结点
{
ListNode *pNew=new ListNode;
pNew->data=value;
pNew->next=NULL;
if(*pHead==NULL)//单链表为空链表
{
*pHead=pNew;
}
else//单链表非空
{
ListNode *pNode=*pHead;
while(pNode->next!=NULL)//先找到尾结点的前驱结点
{
pNode=pNode->next;
}
pNode->next=pNew;
}
}
//删除链表结点考虑两种情况,删除第一个结点,和删除中间结点
void RemoveNode(ListNode**pHead,int value)//删除链表中第一次出现value的结点
{
if(pHead==NULL||*pHead==NULL)
{
return;
}
ListNode *pToBeDeleted=NULL;
if((*pHead)->data==value)//删除第一个结点
{
pToBeDeleted=*pHead;
*pHead=(*pHead)->next;
}
else//删除中间结点
{
ListNode *pNode=*pHead;
while(pNode->next!=NULL&&pNode->next->data!=value)//找到待删除结点的前驱结点
{
pNode=pNode->next;
}
if(pNode->next!=NULL&&pNode->next->data==value)
{
pToBeDeleted=pNode->next;
pNode->next=pNode->next->next;
}
}
if(pToBeDeleted!=NULL)//最后删除结点,如链表中不含有值value则不删除
{
delete pToBeDeleted;
pToBeDeleted=NULL;
}
}
void PrintList(ListNode *pHead)//打印单链表
{
if(pHead==NULL)
{
return;
}
ListNode *pNode=pHead;
while(pNode!=NULL)
{
printf("%d\t",pNode->data);
pNode=pNode->next;
}
cout<<endl;
}
void PrintListReversely(ListNode *pHead)//递归法逆序打印单链表
{
if(pHead==NULL)
{
return ;
}
ListNode *pNode=pHead;
if(pNode->next!=NULL)
{
PrintListReversely(pNode->next);
}
printf("%d\t",pNode->data);
}
ListNode* ReverseList(ListNode *pHead)//反转单链表
{
if(pHead==NULL)
{
return NULL;
}
ListNode *pre=NULL;
ListNode *pcur=pHead;
ListNode *pnext=NULL;
ListNode *pReverseHead=NULL;
while(pcur!=NULL)
{
pnext=pcur->next;
if(pnext==NULL)
{
pReverseHead=pcur;
}
pcur->next=pre;
pre=pcur;
pcur=pnext;
}
return pReverseHead;
}
void SortList(ListNode*pHead)//冒泡法对单链表进行排序
{
if(pHead==NULL)
{
return;
}
int length=0;//单链表的的长度
ListNode *pNode=pHead;
while(pNode!=NULL)
{
pNode=pNode->next;
length++;
}
bool flag=true;
for(int i=0;i<length-1&&flag;i++)
{
flag=false;
pNode=pHead;
for(int j=0;j<length-1-i;j++)//冒泡法对单链表排序
{
if(pNode->data>pNode->next->data)
{
flag=true;
int temp=pNode->data;
pNode->data=pNode->next->data;
pNode->next->data=temp;
}
pNode=pNode->next;//指向下一个结点
}
}
}
int main()
{
ListNode *pNode=NULL;
// cout<<pNode->next->next->data<<endl;
srand(time(NULL));
for(int i=10;i>0;i--)
{
//cout<<rand()%100<<endl;
AddNodeToTail(&pNode,rand()%15);
}
cout<<"排序单链表"<<endl;
SortList(pNode);
PrintList(pNode);
cout<<"反转单链表"<<endl;
pNode=ReverseList(pNode);
PrintList(pNode);
cout<<"删除单链表中结点为值10的第一个结点没有则不删除任何结点"<<endl;
RemoveNode(&pNode,10);
PrintList(pNode);
return 0;
}