双向链表的创建插入删除
1 #include <iostream> 2 #include<fstream> 3 4 using namespace std; 5 //typedef struct Node{ 6 // int value; 7 // struct Node *next; 8 //}Node; 9 class Node{ 10 public : 11 Node():data(0),last(nullptr),next(nullptr){} 12 Node(int bv,class Node* bp1,class Node* bp2):data(bv),last(bp1),next(bp2){} 13 public : 14 int data; 15 class Node* next; 16 class Node* last; 17 }; 18 Node *headNode,*tailNode; 19 int listlen; 20 void initlist(); 21 void inselist(int kdata); 22 void delelist(); 23 void outlist(); 24 25 int main() 26 { 27 int insedata = 0; 28 cin >> listlen; 29 initlist(); 30 cin >> insedata; 31 inselist(insedata); 32 outlist(); 33 delelist(); 34 return 0; 35 } 36 void initlist() 37 { 38 int data; 39 Node *tempNode = nullptr; 40 cin >> data; 41 headNode = new Node(data,nullptr,nullptr); 42 tempNode = headNode; 43 for(int i=1; i<listlen; ++i){ 44 cin >> data; 45 tempNode->next = new Node(data,tempNode,nullptr); 46 tempNode = tempNode->next; 47 } 48 tailNode = tempNode; 49 } 50 void inselist(int kdata) 51 { 52 Node *tempNode = headNode; 53 Node *inseNode = new Node(kdata,nullptr,nullptr); 54 while(tempNode){ 55 if(tempNode->data >= kdata){ 56 break; 57 } 58 tempNode = tempNode->next; 59 } 60 if(tempNode == headNode){ 61 headNode->last = inseNode; 62 inseNode->next = headNode; 63 headNode = inseNode; 64 } 65 else if(tempNode == nullptr){ 66 tailNode->next = inseNode; 67 inseNode->last = tailNode; 68 tailNode = inseNode; 69 } 70 else{ 71 (tempNode->last)->next = inseNode; 72 inseNode->last = tempNode->last; 73 inseNode->next = tempNode; 74 tempNode->last = inseNode; 75 } 76 } 77 void outlist() 78 { 79 Node *tNode = headNode; 80 ofstream outf("out.txt",ios::out); 81 82 while(tNode){ 83 if(tNode == headNode)cout << tNode->data; 84 else cout << " " << tNode->data; 85 tNode = tNode->next; 86 } 87 outf << endl; 88 outf.close(); 89 } 90 void delelist() 91 { 92 Node *tNode = headNode; 93 Node *tnext; 94 while(tNode){ 95 tnext = tNode->next; 96 delete tNode; 97 tNode = tnext; 98 } 99 }
posted on 2018-03-22 16:14 CreatorKou 阅读(246) 评论(0) 编辑 收藏 举报