C++之带头节点单链表的简单操作

来源:互联网 发布:js选择时间段 编辑:程序博客网 时间:2024/05/17 18:26
#ifndef _LINK_H_#define _LINK_H_class List{public:    List();    ~List();    void insert(const int d1);    void tail_insert(const int d1);    void insert_pos(const int d1,const int d);    void remove(const int d1);    void reverse();    void print() const;    int search(const int d1,const int d);private:   struct Node    {        int data;struct Node *next;    };        struct Node *head;};#endif

#include <iostream>#include "List.h"#include <cstdlib>using namespace std;List :: List(){    head = new  Node();    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:: insert(const int d1){    Node *p = new Node();p -> data = d1;    p -> next = head -> next;    head -> next = p;}//尾插void List::tail_insert(const int d1){    Node *p = new Node();p -> data = d1;    Node *temp = head;    while(temp -> next != NULL)    {        temp = temp -> next;    }    temp -> next = p;    p -> next = NULL;}//指定位置插入一个结点void List::insert_pos(const int d1,const int d){        Node *p = new Node();p -> data = d1;    Node *temp = head -> next;    while(temp != NULL)    {        if(temp -> data == d){    p -> next = temp-> next;    temp -> next = p;    break;}temp = temp -> next;    }}int List::search(const int d1,const int d){        Node *p = new Node();p -> data = d1;    Node *temp = head -> next;    while(temp != NULL)    {        if(temp -> data == d)    {    return temp -> data;}    else    {    cout<<"无此数据!"<<endl;    }}}//删除void List::remove(const int d1){    Node * p = head;    Node *temp = p -> next;    while( temp != NULL)    {        if(temp -> data == d1){    p -> next = temp -> next;    delete temp;    temp = temp -> next;}p = temp;temp = temp -> next;    }}//遍历void List :: print() const{    Node *temp = head -> next;    while(temp != NULL)    {        cout << temp -> data <<endl;temp = temp -> next;    }}//逆序void List::reverse(){   Node *p = head;   Node *q = p -> next;   Node *m = q -> next;   while(m != NULL)   {       q -> next = p;       p = q;       q = m;       m = m ->next;   }   q -> next = p;   head -> next -> next = NULL;   head -> next = q;}

#include <iostream>#include "List.h"using namespace std;int main(){    List list;    int i;    for(i = 0; i < 10; i++)    {        list.insert(i+1);//list.tail_insert(i+1);    }    list.remove(6);    list.reverse();//list.search(3,3);    list.print();    return 0;}
搜索写得有点问题!
0 0