单链表:单向有序链表 最后置于空
#pragma once
#include
#include
#include
typedef int DataType;
typedef struct ListNode
{
struct ListNode *_next;
DataType _data;
}ListNode;
void PrintList(ListNode *&pHead)
{
while(pHead)
{
printf("%d->",pHead->_data);
pHead=pHead->_next;
}
printf("NULL\n");
}
ListNode* BuyNode(DataType x)
{
ListNode *tmp=(ListNode *)malloc(sizeof(ListNode));
tmp->_data=x;
tmp->_next=NULL;
return tmp;
}
void PushFront(ListNode *&pHead,DataType x)//首部插入
{
if(pHead==NULL)
{
pHead=BuyNode(x);
}
else
{
ListNode *tmp=BuyNode(x);
tmp->_next=pHead;
pHead=tmp;
}
}
void PopFront(ListNode *&pHead)//首部删除
{
if(pHead!=NULL)
{
ListNode *del=pHead;
pHead=del->_next;
free(del);
}
}
void PushBack(ListNode *&pHead,DataType x)//尾部插入
{
if(pHead==NULL)
{
pHead=BuyNode(x);
}
else
{
ListNode *cur=pHead;
while(cur->_next)
{
cur=cur->_next;
}
cur->_next=BuyNode(x);
}
}
void PopBack(ListNode *&pHead)//尾部删除
{
if(pHead==NULL)
{
return;
}
else if(pHead->_next==NULL)
{
free(pHead);
pHead=NULL;
}
else
{
ListNode *cur=pHead;
ListNode *prev=pHead;
while(cur->_next)
{
prev=cur;
cur=cur->_next;
}
prev->_next=NULL;
free(cur);
}
}
ListNode *Find(ListNode *&pHead,DataType x)//查找
{
ListNode *cur=pHead;
while(cur)
{
if(cur->_data==x)
{
return cur;
}
cur=cur->_next;
}
return NULL;
}
void PopNoHead(ListNode *pos)//删除无头单链表的非尾节点
{
ListNode *del = pos->_next;
assert(pos);
pos->_data = del->_data;
pos->_next = del->_next;
free(del);
del=NULL;
}
//Test.cpp#include
#include "List.h"
void Test1()//输入/出、查找
{
ListNode *ret=NULL;
ListNode *list=NULL;
PushFront(list,1);
PushFront(list,2);
PushFront(list,3);
PushFront(list,4);
PushFront(list,5);
PrintList(list);
Find(list,4);
PopFront(list);
PopFront(list);
PopFront(list);
PopFront(list);
PrintList(list);
}