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;
}