注重基础才是笔试面试的王道。在准备实习的过程中把数据结构的几个基本点实现了一遍,大家多交流提高~
每一篇都由一个.h和一个.cpp文件组成,实现方便,验证直观。
如果您是像我一样的初学者,建议敲一遍代码并且单步跟踪一遍,对加深理解很好。
第一篇。单链表~
LinkList.h头文件中代码:
#include<iostream>
using namespace std;
#ifndef LinkList_H
#define LinkList_H
template <class T>
struct Node
{
T data;
Node<T>* next;
};
template <class T>
class LinkList
{
public:
LinkList(T a[],int n);
~LinkList();
void Insert(int i,T x);
T Delete(int i);
int Locate(T x);//按值查位数
T Get(int i);//按位数返回值
void PrintList();
private:
Node<T>* first;
};
template <class T>
T LinkList<T>::Get(int i)
{
int j = 1;
Node<T>* s = first->next;
while( s && j<i)
{
s = s->next;
j++;
}
if(!s)
throw"位置!";
else
return s->data;
}
template <class T>
int LinkList<T>::Locate(T x)
{
int j = 1;
Node<T>* p = first->next;
while( p && p->data != x)
{
p = p->next;
j++;
}
if(p)
return j;
else
return -1;
}
template <class T>
T LinkList<T>::Delete(int i)
{
int j = 0;
Node<T>* p = first;
while( p && j<i-1)
{
p = p->next;
j++;
}
if(!p || !p->next)
throw "位置!";
else
{
Node<T>* s = p->next;
T x = s->data;
p->next = s->next;
delete s;
s= NULL;
return x;
}
}
template <class T>
void LinkList<T>::Insert(int i,T x)
{
int j = 0;
Node<T>* p = first;
while( p && j<i-1)
{
p = p->next;
j++;
}
if(!p)
throw "位置!";
else
{
Node<T>* s = new Node<T>;
s->data = x;
s->next = p->next;
p->next = s;
}
}
template <class T>
LinkList<T>::LinkList(T a[],int n)
{
//尾插法
first = new Node<T>;
Node<T>* r = first;
for(int j=0;j<n;j++)
{
Node<T>* s = new Node<T>;
s->data = a[j];
r->next = s;
r = s;
}
r->next = NULL;
//头插法
/*first = new Node<T>;
first->next = NULL;
for(int i = 0;i<n;i++)
{
Node<T>* s = new Node<T>;
s->data = a[i];
s->next = first->next;
first->next = s;
}*/
}
template <class T>
LinkList<T>::~LinkList()
{
Node<T> *p,*q;
p = first;
while(p)
{
q = p;
p = p->next;
delete q;
q = NULL;
}
}
template <class T>
void LinkList<T>::PrintList()
{
Node<T> *p;
p = first->next;
while(p)
{
cout<<p->data<<" ";
p = p->next;
}
}
#endif
.cpp中验证代码为
#include "stdafx.h"
#include "LinkList.h"
int _tmain(int argc, _TCHAR* argv[])
{
int r[] = {100,80,60,40,20};
LinkList<int> a(r,5);
try
{
a.Insert(6,10);//在第几位插入值为
}
catch(char *s)
{
cout<<s<<endl;
}
try
{
int x = a.Delete(6);//删除第几位
cout<<x<<endl;
}
catch(char *s)
{
cout<<s<<endl;
}
int y = a.Locate(10);//返回值为*的所在位置
cout<<y<<endl;
try
{
int z = a.Get(2);//第n位上的值
cout<<z<<endl;
}
catch(char* s)
{
cout<<s<<endl;
}
a.PrintList();//打印出来
return 0;
}
完~