单链表头插法和尾插法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010164190/article/details/88771445
#include <iostream>
using namespace std;
class List{
public:
  List(){create_List();}
  ~List(){}
  void create_List();
  void insert_head(const int &d);
  void insert_end(const int &d);
  void print();
 private:
  struct Node{
  int data;
  Node *next;
  Node(const int &d) : data(d),next(NULL){ }
};

  Node *head;
  Node *newhead;
};
//创建单链表头节点,head->data = 0;head->next = NULl
void List::create_List(){
  head = new Node(0);
}
//头插法
void List::insert_head(const int &d){
  for(int i = 0; i < d; i++){
    Node *p = new Node(i);
    p->next = head->next;
    head->next = p;
  }
}
//尾插法
void List::insert_end(const int &d){
  Node *cur = head;
  for(int i = 0; i < d; i++){
    Node *p = new Node(i);
    cur->next = p;
    cur = p;
  }
  cur->next = NULL;
}

void List::print(){
  while(head->next){
    head = head->next;
    cout << head->data << " ";
  }
  cout << endl;
}

int main(){
  List list;
  list.insert_head(4);
  list.print();
  list.insert_end(4);
  list.print();
  return 0;
}

猜你喜欢

转载自blog.csdn.net/u010164190/article/details/88771445