单链表的链接存储结构实现

来源:互联网 发布:中国省市区json数据 编辑:程序博客网 时间:2024/06/04 19:29
#include <iostream>using namespace std;class Node{public:int element;Node *next;};class List{private:    Node *head;public:List();//无参构造函数      List(int a[], int n); //有参构造函数      ~List();//析构函数void Length();   //求长度int Min();void Delete( int n);void Inserte( int m,int n);    //在第n个位置插入mvoid PrintList();//遍历操作};List::List(){head = new Node;     ///生成一个头结点      head->next = NULL;   ///头结点的指针域置空}//此方法会生成逆序的链表/*List::List(int a[],int n){int i;      Node* s;      head = new Node;      head->next = NULL;   ///初始化一个空链表      for (i = 0; i < n; i++) {          s = new Node;          s->element = a[i];   ///为每个数组元素建立一个数据域为a[i]的结点          s->next = head->next;          head->next = s;   ///将结点s插入到头指针之后      }  }*///此方法会生成正常序链表List::List(int a[],int n)  {      head = new Node; //生成头结点      Node *r,*s;      r = head; //尾指针初始化      for (int i = 0; i < n; i++) {          s = new Node;           s->element = a[i]; //为每个数组元素建立一个结点          r->next = s;          r = s; //将结点s插入到终端结点之后      }    r->next=NULL;}  List::~List(){Node* q;      while (head) {   ///释放单链表每一个结点的存储空间        q = head;   ///暂存被释放结点          head = head->next;   ///head指向被释放结点的下一个结点        delete q;      }}void List::Length(){Node *p;p=head;int count = 0;    while (p) {p = p->next;count++;}cout << count-1 <<endl;}int List::Min(){Node *s,*z;z = head->next;int min = 1000;while (z) {s = z;if (s->element < min) {min = s->element;}z = z->next;}cout << min <<endl;return min;}void List::Delete(int n){Node *b,*c;b = head;while (b) {if(b->element != n) {c = b;b = b->next;}else {c->next = b->next;b = b->next;return;}}}void List::Inserte(int m,int n){Node *q,*p,*s;s = new Node;p = head;for ( int i = 0; i < n; i++){q = p;p = p->next;}s->element = m;s->next = q->next;q->next = s;}void List::PrintList(){    Node* p = head->next;  ///工作指针p初始化      while (p) {          cout << p->element;          p = p->next;   ///工作指针后移,注意不能写成p++      }  } int main(){int a[]={1,2,3,4,5};List B(a,5);        B.Length();//int n = B.Min();//B.Delete(n);//B.Inserte(6,2);B.PrintList();cout << endl;return 0;}


 

0 0
原创粉丝点击