单循环链表中各种函数的实现

List.h

#ifndef _LIST_H
#define _LIST_H

#include<iostream>
#include<assert.h>
using namespace std;

#define ElemType int

typedef struct Node
{
	ElemType data;
	struct Node *next;
}Node, *PNode;

typedef struct List
{
	PNode first;
	PNode last;
	size_t size;
}List;

//
void InitList(List *list);
bool push_back(List *list, ElemType x);
bool push_front(List *list, ElemType x);
bool pop_back(List *list);
bool pop_front(List *list);
Node* Find(List *list, ElemType key);
bool delete_val(List *list, ElemType key);
void ShowList(List *list);
void clear(List *list);
void destroy(List *list);
void resver(List *list);
bool insert_val(List *list,ElemType key);
#endif




List.cpp

#include"List.h"


void InitList(List *list)
{
	Node *s=(Node *)malloc(sizeof(Node));
    assert(s!=0);
	s->next=NULL;

    list->first=list->last=s;
	list->size=0;
}
bool push_back(List *list, ElemType x)
{
    Node *s=(Node *)malloc(sizeof(Node));
    if(s==NULL)
		return false;
	s->data=x;
	s->next=NULL;

	list->last->next=s;
	list->last=s;
	list->size++;
	return true;
}
bool push_front(List *list, ElemType x)
{
    Node *s=(Node *)malloc(sizeof(Node));
    if(s==NULL)
		return false;

	s->data=x;
	s->next=list->first->next;
	list->first->next=s;
	if(list->size==0)
	{
		list->last=s;
	}
	list->size++;
	return true;
}
bool pop_back(List *list)
{
	if(list->size==0)
		return false;
    Node *pre=list->first;
	while(pre->next!=list->last)
	{
		pre=pre->next;
	}
	pre->next=NULL;
	free(list->last);
	list->last=pre;
	list->size++;
	return true;
}
bool pop_front(List *list)
{
	if(list->size==0)
		return false;
	Node *p=list->first->next;
	if(list->size==1)
	{
		free(p);
		list->first->next=NULL;
		list->last=list->first;
	}
	else
	{
        list->first->next=p->next;
	    free(p);
	}
	list->size--;
	return true;
}
Node* Find(List *list, ElemType key)
{
	Node *p=list->first->next;
	while(p!=NULL&&p->data!=key)
		p=p->next;
	return p;
}
bool delete_val(List *list, ElemType key)
{
	Node *p=list->first;
	Node *q=p->next;
	while(q!=NULL)
	{
		if(q->data==key)
		{
			if(q==list->last)
				list->last=p;
			free(q);
		    list->size--;
			return true;
		}
		p=p->next;
	}
    return false;
}
void ShowList(List *list)
{
	Node *p=list->first->next;
	while(p!=NULL)
	{
		cout<<p->data<<"-->";
		p=p->next;
	}
	cout<<"NULL"<<endl;
}
void clear(List *list)
{
	Node *p = list->first->next;
	while(p != NULL)
	{
		list->first->next = p->next;
		free(p);
		p = list->first->next;
	}
	list->last = list->first;
	list->size = 0;
}
void destroy(List *list)
{
	clear(list);
	free(list->first);
	list->first = list->last = NULL;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值