C++创建链表

来源:互联网 发布:mysql中的日期函数 编辑:程序博客网 时间:2024/06/14 17:32
首先是Node.h#pragma once#include<iostream>using namespace std;class Node{public: Node() {  data = 0;  next = NULL; }; Node * next; int data; };然后是LinkList.h#pragma once#include<iostream>#include"Node.h"using namespace std;class LinkList{public: LinkList(); ~LinkList(); void CreatLinkList(int l); void Print();private: int length=0; Node * head,*tail;};LinkList::LinkList(){ head = new Node; tail = head; length++;}LinkList::~LinkList(){ Node* temp; int i = 0; while (head!=NULL) {  temp = head;  head = head->next;  delete temp;  i++; }}void LinkList::CreatLinkList(int l){ length = l; if (length == 0) {  cout << "Failed to Creat!"<<endl; } else {  head->next = new Node;  tail = head->next;  cout << "Input the data of this node: ";  cin >> tail->data;  for (int i = 1; i < length; i++)  {   tail->next = new Node;   tail = tail->next;   cout<< "Input the data of this node: ";   cin >> tail->data;   tail->next = NULL;  } }}void LinkList::Print(){ if (length == 0) {  cout << "Empty list;"<<endl; } else {  Node * p=head->next;  while (p != NULL)  {   cout << p->data << endl;   p = p->next;  } }}最后在 LinkList.cpp中测试#pragma once#include<iostream>#include"Node.h"#include"LinkList.h"using namespace std;int main(){ LinkList L; L.CreatLinkList(5); L.Print();}