#ifndef _LINK_H_
#define _LINK_H_
class List
{
public:
List();
~List();
void insert(const int d1);
void tail_insert(const int d1);
void insert_pos(const int d1,const int d);
void remove(const int d1);
void reverse();
void print() const;
int search(const int d1,const int d);
private:
struct Node
{
int data;
struct Node *next;
};
struct Node *head;
};
#endif
#include <iostream>
#include "List.h"
#include <cstdlib>
using namespace std;
List :: List()
{
head = new Node();
head -> next = NULL;
}
List :: ~List()
{
Node *p = head -> next;
while(p != NULL)
{
head -> next = p -> next;
delete p;
p = head -> next;
}
delete head;
head = NULL;
}
//从头插入一个结点
void List:: insert(const int d1)
{
Node *p = new Node();
p -> data = d1;
p -> next = head -> next;
head -> next = p;
}
//尾插
void List::tail_insert(const int d1)
{
Node *p = new Node();
p -> data = d1;
Node *temp = head;
while(temp -> next != NULL)
{
temp = temp -> next;
}
temp -> next = p;
p -> next = NULL;
}
//指定位置插入一个结点
void List::insert_pos(const int d1,const int d)
{
Node *p = new Node();
p -> data = d1;
Node *temp = head -> next;
while(temp != NULL)
{
if(temp -> data == d)
{
p -> next = temp-> next;
temp -> next = p;
break;
}
temp = temp -> next;
}
}
int List::search(const int d1,const int d)
{
Node *p = new Node();
p -> data = d1;
Node *temp = head -> next;
while(temp != NULL)
{
if(temp -> data == d)
{
return temp -> data;
}
else
{
cout<<"无此数据!"<<endl;
}
}
}
//删除
void List::remove(const int d1)
{
Node * p = head;
Node *temp = p -> next;
while( temp != NULL)
{
if(temp -> data == d1)
{
p -> next = temp -> next;
delete temp;
temp = temp -> next;
}
p = temp;
temp = temp -> next;
}
}
//遍历
void List :: print() const
{
Node *temp = head -> next;
while(temp != NULL)
{
cout << temp -> data <<endl;
temp = temp -> next;
}
}
//逆序
void List::reverse()
{
Node *p = head;
Node *q = p -> next;
Node *m = q -> next;
while(m != NULL)
{
q -> next = p;
p = q;
q = m;
m = m ->next;
}
q -> next = p;
head -> next -> next = NULL;
head -> next = q;
}
#include <iostream>
#include "List.h"
using namespace std;
int main()
{
List list;
int i;
for(i = 0; i < 10; i++)
{
list.insert(i+1);
// list.tail_insert(i+1);
}
list.remove(6);
list.reverse();
//list.search(3,3);
list.print();
return 0;
}
搜索写得有点问题!
转载请注明原文地址: https://ju.6miu.com/read-4686.html