ListNode.h
#include<malloc.h>
#include<assert.h>
typedef int DataType;
typedef struct ListNode
{
struct ListNode* _next;
DataType _data;
}ListNode;
ListNode* BuyNode(DataType x)//创建一个结点
{
ListNode* tmp=(ListNode*)malloc(sizeof(ListNode));
tmp->_data =x;
tmp->_next=NULL;
return tmp;
}
void PrintList(ListNode* pHead)//打印
{
ListNode* p=pHead;
while(p != NULL)
{
printf(" %d -> ",p->_data );
p=p->_next ;
}
printf("NULL");
printf("\n");
}
void PushFront(ListNode*& pHead,DataType x)//头插
{
ListNode* tmp=NULL;
if(pHead == NULL)
{
pHead=BuyNode(x);
}
else
{
tmp=BuyNode(x);
tmp->_next =pHead;
pHead=tmp;
}
}
void PopFront(ListNode*& pHead)//头删
{
if(pHead)
{
ListNode* del=pHead;
pHead=pHead->_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)
{
pHead=NULL;
free(pHead);
}
else
{
ListNode* cur=pHead,*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 Insert(ListNode * pos,DataType x)//插入
{
assert(pos);
ListNode* tmp=BuyNode(x);
tmp->_next =pos->_next ;
pos->_next =tmp;
}
void Erase(ListNode* &pHead,ListNode* pos)//删
{
if(pHead==pos)
{
pHead=pHead->_next ;
free(pos);
}
else
{
ListNode* cur=pHead;
while(cur->_next !=pos)
{
cur=cur->_next ;
}
cur->_next =pos->_next ;
free(pos);
}
}
ListNode* FindMiddleListNode(ListNode* pHead)//查找中间节点
{
if(pHead == NULL ||pHead->_next == NULL)
{
return pHead;
}
ListNode *p1 = pHead;
ListNode *p2 = pHead;
while((p2->_next != NULL) && (p2->_next ->_next != NULL ))
{
p2 = p2->_next->_next;
p1 = p1->_next;
}
return p1;
}
void Delete_List(ListNode *cur)//删除非尾节点
{
assert(cur);
ListNode* next = cur->_next;
if(next != NULL)
{
cur->_next = next->_next;
cur->_data = next->_data;
}
}
test.cpp
#include<stdio.h>
#include<stdlib.h>
#include"ListNode.h"
void test1()//PushFront(s,3);//PopFront(s);//PushBack(s,3);//PopBack(s);
{
ListNode* s=NULL;
PushFront(s,1);
PushFront(s,2);
PushFront(s,3);//头插
PopFront(s);//头删
PushBack(s,3);//尾插
PopBack(s);//尾删
PrintList(s);
}
void test2()//Find(s,1)//Inser//Erase;
{
ListNode* s=NULL;
Insert(s,2);//插入
Find(s,1);//查找
Erase(s,s);
PrintList(s);
}
void test3()//查找中间节点,删除非尾节点
{
ListNode* s=NULL;
PushFront(s,1);
PushFront(s,2);
PushFront(s,3);
PushFront(s,4);
PushFront(s,5);
PrintList(s);
ListNode* ret=FindMiddleListNode(s);//查找中间节点
PrintList(ret);
Delete_List(s);//删除非尾节点
PrintList(s);
}
int main()
{
//test1();
//test2();
test3();
system("pause");
return 0;
}原文:http://760470897.blog.51cto.com/10696844/1753228