单链表

node.h

typedef int elementype;

class Node
{
public:
	elementype data;		//当前数据
	Node *next;				//下一结点地址
};

linklist.h

#include "node.h"
#include <iostream>

class linklist
{
public:
	Node Header;		//头结点
	int length;		//链表长度
	
	void Init(int n);			//创建含有n个结点的的链表
	bool Clear();				//清空链表
	bool Insert(int i,elementype x);	//在第i个元素前插入元素x
	void Show();
	void Push(elementype x);		//在链表尾部插入元素x
	bool Delete(int i);		        //删除第i个结点
	int Find(elementype x);			//寻找元素x,存在返回结点位置,不存在返回0
	bool Reverse();				//反转链表
};

linklist.cpp

#include "linklist.h"

void linklist::Init(int n)
{
	std::cout<<"请依次输入"<<n<<"个数据"<<std::endl;
	Header.data=0;
	length = n;
	Node *last_node;
	last_node = &Header;
	for(int i=1;i<=n;i++)
	{
		Node *next_node = new Node;
		std::cin>>next_node->data;
		last_node->next = next_node;
		last_node =  next_node;
	}
	last_node->next = NULL;
}

void linklist::Show()
{
	Node *temp = Header.next;
	while(temp->next != NULL)
	{
		std::cout<<temp->data<<" ";
		temp = temp->next;
	}
	std::cout<<temp->data;
	std::cout<<std::endl;
}

void linklist::Push(elementype x)
{
	Node *temp = Header.next;
	while( temp->next != NULL )
		temp = temp->next;
	Node *newNode = new Node;
	temp->next = newNode;
	newNode->data = x;
	newNode->next = NULL;
	length++;
}

bool linklist::Insert(int i,elementype x)
{
	if(i<1 || i>length)
	{std::cout<<"Error";return false;}

	Node *temp = &Header;
	int count = 0;
	while(temp->next != NULL)
	{
		count++;
		if(count == i)
			break;
		temp = temp->next;
	}

	Node *newNode = new Node;
	newNode->data = x;
	newNode->next = temp->next;
	temp->next = newNode;
	length++;
	return true;
}

bool linklist::Delete(int i)
{
	if(i<1 || i>length)
	{std::cout<<"Error";return false;}

	Node *temp = &Header;
	int count = 0;
	while(temp->next != NULL)
	{
		count++;
		if(count == i)
			break;
		temp = temp->next;
	}
	Node *tempNode = temp->next;
	temp->next = tempNode->next;
	delete tempNode;
	length--;
	return true;
}

int linklist::Find(elementype x)
{
	int count=0;
	Node *temp = Header.next;
	while(temp->next != NULL)
	{
		count++;
		if(temp->data == x)
			return count;
		temp = temp->next;
	}

	if(temp->data == x)		//最后一个元素
		return length;

	return 0;
}

bool linklist::Reverse()
{
	if(length == 0 || length == 1)
		return true;

	Node *temp1 = Header.next->next;
	Node *temp2;
	Header.next->next = NULL;
	while(temp1->next != NULL)
	{
		temp2 = temp1->next;
		temp1->next = Header.next;
		Header.next = temp1;
		temp1 = temp2;
		temp2 = temp1->next;
	}

	temp1->next = Header.next;
	Header.next = temp1;
	return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值