数据结构笔记之二链表

来源:互联网 发布:qq变声软件 编辑:程序博客网 时间:2024/05/21 02:50

链表的定义,以及push_front,pop_front函数的定义

#include <iostream>using namespace std;struct Node {int x;Node *next;};class List{private:Node *Head;public:List();~List();void push_front(int x);//从前面插入元素void pop_front();//删除第一个元素int size();//元素个数,除头节点void push_back(int x);//从后面插入元素void pop_back();//删除最后一个元素void Print();};List::List(){Head=new Node;Head->x=0;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::push_front(int x){Node *s=new Node;Node *p=Head->next;s->x=x;s->next=Head->next;Head->next=s;}void List::pop_front(){Node *p=Head->next;Head->next=p->next;delete p;}int List::size(){int i=0;Node *p=Head->next;while(p!=NULL){p=p->next;i++;}return i;}void List::push_back(int x){Node *p=Head->next;Node *q=Head;while(p!=NULL){q=p;p=p->next;}p=new Node;p->x=x;p->next=NULL;q->next=p;}void List::pop_back(){Node *p=Head->next;for (int i=0;i<size()-2;i++){p=p->next;}p->next=NULL;}void List::Print(){Node *p=Head->next;while(p!=NULL){cout<<p->x<<"";p=p->next;}cout<<endl;}int main(int argc, char* argv[]){List list;list.push_front(1);list.push_front(2);list.push_front(3);list.push_front(4);list.push_front(5);list.Print();list.pop_front();list.Print();list.push_back(6);list.Print();list.pop_back();list.Print();cout<<"size:  "<<list.size()<<endl;return 0;}



运行结果:

5       4       3       2       1

4       3       2       1

4       3       2       1       6

4       3       2       1

size:  4