c程序语言的基本单列表,单链表(C语言)基本操作

单链表:单向有序链表 最后置于空

#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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值