一窥--顺序表和单链表

#include<iostream> #include<string> using namespace std; typedef int ElemType; struct Node{ ElemType data;//数据域 node->data struct Node *next;//指针域 node->next };string CreateListHead(Node *L){//L是现在是空表的头指针 L->next = NULL;//头结点初始化 Node *p = new Node; if(!p)return "Create fail"; cin>>p->data; while(p->data){//当输入为0,停止创建 p->next = L->next; L->next = p; p = new Node; cin>>p->data; } delete p; return "Create list from head!"; } string CreateListTail(Node *L){ L->next = NULL; Node *p = new Node; Node *t = L;//指向尾结点 if(!p) return "Create fail (from tail)"; cin>>p->data; while(p->data){ t->next = p; t = p; p = new Node; cin>>p->data; } t->next = NULL;//最后指向NULL delete p; return "Create list from tail!"; } int GetElem(Node *L,int index){ int j=1; Node *p = new Node; p = L->next;//指向头结点 while(p && j<index){ p = p->next; j++; } //p&&j<i 条件取反 if (!p){ return -1; } return p->data; } string ListInsert(Node *L,int index,ElemType e){int j; Node *p,*s; p = new Node; s = new Node; if(!p && !s)return "Insert fail"; p = L; //注意插入操作,体现头结点的好处:统一处理的代码 j = 1; while(p && j<index){ p = p->next; j++; } if (!p) return "Index out of change"; s->data = e; s->next = p->next; p->next = s; //这里p和s不能删除return "Inserted!"; } string ListDelete(Node *L,int index,ElemType e){ int j; Node *p,*s= new Node; p = L;//p指向头 j = 1; while(p->next && j<index){ //p->next 是要删除的,这样,p就保存了删除的结点前一个结点的信息 p = p->next; ++j; } if(!(p->next)){ return "Index out of change"; } s = p->next; p->next = s->next; delete s; //删除结点 return "Deleted!"; } void ShowList(Node *L){ Node *p = L->next;if(!p) cout<<"List is empty"<<endl; while(p){ cout<<p->data<<" "; p = p->next; } cout<<endl; } int main(){ Node *node = new Node; CreateListHead(node); //头插法,倒着插入 ,1,2,3 ShowList(node); cout<<ListInsert(node,2,-10)<<endl; ShowList(node); Node *_node = new Node; CreateListTail(_node); ShowList(_node);cout<<ListInsert(_node,2,-10)<<endl; ShowList(_node);delete node; delete _node; return 0; }

posted @ 2017-06-13 21:10  张玉宝  阅读(146)  评论(0编辑  收藏  举报
友情链接:回力鞋 | 中老年高档女装 | 武汉英语学校 | 托福网课 | 托福培训