标签:输入 指定 com 注意 list 删除 lin 元素 单链表
单链表有两个部分,一个是数据域,用来储存相应的数据;另一个是指针域,用来储存下一个结点的位置。由于单链表的结点的物理位置是不连续的,因此能够提高存储空间的利用率,同时有利于插入和删除的操作。
1 class Node{
2 public:
3 int data;
4 Node *next;
5 };
1 class LinkList{
2 public:
3 LinkList();
4 ~LinkList();
5 void h_Insert(); //头插法
6 void r_Insert(); //尾插法
7 void Insert( int mes, int index ); //在指定位置插入元素
8 void Delete( int index ); //删除指定位置元素
9 void show();
10
11 private:
12 Node *head; //头指针
13 Node *rear; //尾指针
14 int length;
15 };
1 head = new Node;
2 if( head == NULL ){
3 cout << "Failed to creat a list." << endl;
4 exit(-1);
5 }
6 head->next = NULL;
7 rear = head;
8 length = 0;
注意:这样输出的元素的顺序与输入元素的顺序相反
1 void LinkList :: h_Insert() 2 { 3 int data; 4 while( cin>>data ){ 5 Node *node = new Node; 6 if( node == NULL ){ 7 cout << "Failed to head insert a node." << endl; 8 exit(-1); 9 } 10 node->data = data; 11 node->next = head->next; 12 head ->next = node; 13 14 length++; 15 } 16 cout << "Success to head insert." <<endl; 17 }
注意:这样输出的元素的顺序与输入元素的顺序相同
1 void LinkList :: r_Insert() 2 { 3 int data; 4 while( cin>>data ){ 5 Node *node = new Node; 6 if( node == NULL ){ 7 cout << "Failed to rear insert a node." << endl; 8 exit(-1); 9 } 10 node->data = data; 11 node->next = NULL; 12 rear->next = node; 13 rear = node; 14 15 length++; 16 } 17 18 cout << "Success to rear insert." <<endl; 19 }
注意:插入元素的位置是否在链表合理的范围内
1 void LinkList :: Insert( int mes, int index ) 2 { 3 int i = 0; 4 Node *p = head; 5 Node *node = new Node; 6 node->data = mes; 7 while( i < index-1 && p && index>0){ 8 i++; 9 p = p->next; 10 } 11 if( !p || i > length || index<=0 ){ 12 cout << "Fail to insert " << mes << " in " << index <<" ."<<endl; 13 exit(-1); 14 } 15 node->next = p->next; 16 p->next = node; 17 18 length++; 19 20 cout << "Success to insert a data." << endl; 21 }
注意:删除元素的位置是否在链表合理的范围内
1 void LinkList :: Delete( int index ) 2 { 3 int i = 0; 4 Node *p = head; 5 if( !p || index > length || index<=0 ){ 6 cout << "Fail to delete in " << index <<" ."<<endl; 7 exit(-1); 8 } 9 while( i < index-1 && p && index>0){ 10 i++; 11 p = p->next; 12 } 13 Node *q = p->next; 14 p->next = q->next; 15 delete q; 16 length--; 17 cout << "Success to delete a data." << endl; 18 }
标签:输入 指定 com 注意 list 删除 lin 元素 单链表
原文地址:https://www.cnblogs.com/flyingfishesss/p/12202642.html