#include <cstdlib> #include <iostream> using namespace std; int const MAX_VAL = 100; typedef struct _NODE { int value; struct _NODE *next; _NODE(int value) : value(value), next(NULL){}; }NODE, *PTRNODE; PTRNODE insert(PTRNODE &root, int pos, int value) { if(root == NULL) root = new NODE(value); else { PTRNODE newNode = new NODE(value); PTRNODE curNode = root; while(pos-- > 1 && curNode->next != NULL) curNode = curNode->next; if(pos == 0) { newNode->next = curNode->next; curNode->next = newNode; } else if(pos < 0) { newNode->next = root; root = newNode; } else curNode->next = newNode; } return root; } int deleteNode(PTRNODE root, int pos) { if(root == NULL) return -1; int res = 0; PTRNODE curNode = root, temp; while(pos--> 1 && curNode->next != NULL) curNode = curNode->next; if(pos == 0) { temp = curNode->next; curNode->next = curNode->next->next; } else if(pos < 0) { temp = root; root = root->next; } else { temp = curNode; curNode = NULL; } res = temp->value; delete temp; return res; } void display(PTRNODE root) { PTRNODE temp = root; while(temp != NULL) { cout << temp->value << " -> "; temp = temp->next; } cout << endl; } void clear(PTRNODE &root) { if(root == NULL) return; PTRNODE curNode = root; while(curNode != NULL) { PTRNODE temp = curNode; curNode = curNode->next; delete temp; } root = NULL; } void revert(PTRNODE &root) { PTRNODE rev = NULL, temp = NULL; while(root != NULL) { temp = root->next; root->next = rev; rev = root; root = temp; } root = rev; } int main(int argc, char *argv[]) { PTRNODE root = NULL; for(int i=1; i<11; i++) insert(root, i, i); cout << "init list is: " << endl; display(root); cout << "please input a new value an is pos to insert: "; int newValue, pos; cin >> newValue >> pos; insert(root, pos, newValue); cout << "after insert: " << endl; display(root); cout << "please input a pos to delete: "; int delePos, deleVal; cin >> delePos; deleVal = deleteNode(root, delePos); cout << "delete value is: " << deleVal << endl; cout << "after delete: " << endl; display(root); cout << "revert list: " << endl; revert(root); display(root); clear(root); system("PAUSE"); return EXIT_SUCCESS; }