您的位置:首页 > 编程语言 > C语言/C++

单链表(C语言)基本操作

2016-03-28 20:34 459 查看
单链表:单向有序链表 最后置于空

#pragma once
#include<string.h>
#include<malloc.h>
#include<assert.h>

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<stdio.h>
#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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 单链表 基本操作