基础内容,数据合法性注意。(考察知识点:手写,基础)
#include <iostream> using namespace std; typedef struct node{ int data; node *next; }node; node* Create(){ node *head, *p, *q; int x = 0; head = new node; head -> next = NULL; head -> data = 0; while( true ){ cout << "请输入数据:" << endl; cin >> x; if( x == 0 ) break; p = new node; p -> data = x; if( head -> data == 0 ) head -> next = p; else q -> next = p; q = p; head -> data++; } q -> next = NULL; return head; } int Lenth( node *head ){ int len = 0; node *p; p = head -> next; while( p != NULL ){ len++; p = p -> next; } return len; } void Print( node *head ){ if( head -> next == NULL ){ cout << "空表" << endl; return; } node *p = head -> next; //表头存储的链表个数(长度) cout << "表头数据个数:" << head -> data << endl; while( p != NULL ){ cout << p -> data << endl; p = p -> next; } } node *Seach( node *head, int pos ){ if( pos < 0 ?? pos > head -> data ){ cout << "查找位置错误" << endl; return NULL; } node *p = head -> next; if( pos == 0 ){ return head; } if( p == NULL ){ cout << "空表" << endl; return NULL; } //(一)不使用表头存储数据 while( --pos ){ if( ( p = p -> next ) == NULL ){ cout << "查找数据超出链表范围" << endl; break; //return NULL;二者结果一样 } } //(二)使用表头存储数据的情况,上面pos > head -> data已经做了异常处理 /*while( pos-- ){ p = p -> next; }*/ return p; } node *Insert( node *head, int pos, int data ){ node *temp = new node; temp -> next = NULL; temp -> data = data; node *q = Seach( head, pos ); temp -> next = q -> next; q -> next = temp; head -> data++; return head; } node *Delete( node *head, int pos ){ node *p = head -> next; p = Seach( head, pos - 1 ); node *temp = p -> next; if( p != NULL && temp != NULL ){ p -> next = temp -> next; delete temp; //赋值为空,避免野指针 temp = NULL; } head -> data--; return head; } int main() { //建树(链表) node *head = Create(); //打印数据 Print( head ); //统计长度 cout <<"链表长度:"; int Len = Lenth( head ); cout << Len << endl; //查找节点 int pos(0), data( 0 ); cout << "查找节点,输入pos:"; cin >> pos; node *p = Seach( head, pos ); cout << p -> data << endl; //插入节点 cout << "插入节点,输入pos和data:"; cin >> pos >> data; head = Insert( head, pos, data ); Print( head ); cout << "删除节点,输入pos:"; cin >> pos; head = Delete( head, pos ); Print( head ); return 0; }