单链表头插法和尾插法

#include 
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;
}

 

你可能感兴趣的:(经典算法,Android,系统笔试题)