1.算法描述
数据结构与算法分析C++版:3.11
实现一个有序单链表,要求能返回链表大小,打印链表,检测x是否在链表(在则删除,否则添加)
2.实现
List.h
#ifndef LIST_H
#define LIST_H
#include <iostream>
template<class T>
struct Node{
Node<T>* next;
T data;
};
template<class T>
class List{
public:
List(){
len = 0;
first = new Node<T>;
first->next = NULL;
}
List(T a[], int n){
len = 0;
first = new Node<T>;
first->next = NULL;
for(int i=0; i<n; i++){
//有序插入元素
insertData(a[i]);
}
}
~List(){ release(); };
//长度
int length(){
return len;
}
//长度(通过遍历链表)
int getLength(){
int length=0;
Node<T>* r = first->next;
while(r){
length++;
r = r->next;
}
return length;
}
//打印链表
void printList(){
Node<T>* r = first->next;
std::cout<<"[";
while(r){
std::cout<<r->data<<" ";
r = r->next;
}
std::cout<<"]"<<std::endl;
}
//检测元素是否存在
bool isExsit(T x){
Node<T> *r = first->next;
bool b = true;
while(r && r->data != x){
r = r->next;
}
if(!r){
b = false;
}
return b;
}
//添加或删除存在元素(存在则删除,不存在则添加)
void findAddOrDelete(T x){
Node<T> *r = first->next, *p=first, *t;
while(r && r->data != x){
p = r;
r = r->next;
}
if(!r){
insertData(x);
}else{
//因为序列是有序的,删除连续相同的x
while(r && r->data == x){
t = r;
p->next = t->next;
delete t;
r = p->next;
len--;
}
}
}
//有序插入元素
void insertData(T x){
Node<T> *t = first->next, *p=first;
Node<T> *r = new Node<T>;
r->data = x;
r->next = NULL;
while(t && t->data < x){
p = t;
t = t->next;
}
p->next = r;
r->next = t;
len++;
}
private:
Node<T>* first;
int len;//存储链表长度
void release(){
Node<T> *r = first;
while(r->next){
Node<T> *t = r->next;
r->next = t->next;
delete t;
}
first->next = NULL;
}
};
#endif
main.cpp
#include <iostream>
#include "list.h"
using namespace std;
int main( ){
int a[] = {3,11,2,8,4,5,3,6,8,8,8};
List<int> l(a, 11);
cout<<"length:"<<l.length()<<endl;
l.printList();
cout<<l.isExsit(32)<<" "<<l.isExsit(8)<<endl;
l.findAddOrDelete(7);
cout<<"length:"<<l.length()<<endl;
l.printList();
l.findAddOrDelete(8);
cout<<"length:"<<l.length()<<endl;
l.printList();
return 0;
}
3.总结
难度没什么,主要是考察链表的基本操作,边界检查,尤其是使用指针的时候尤其注意,指针检查!
4.删除