关于C++单链表插入和删除。。不造为什么编译过了然而运行出错,求大神援手! 20
#include<iostream>usingnamespacestd;template<classT>structNode{Tdata;Node<T>*next;};t...
#include <iostream>using namespace std;template<class T>struct Node{ T data; Node<T> *next;};template<class T>class LinkList{public: LinkList(); LinkList(T a[], int n); ~LinkList(); void PrintList(); T Delete(int i); void Insert(int i,T x);private: Node<T> *first;};template<class T>LinkList<T>::LinkList(){ first=new Node<T>; first->next=NULL;}template<class T>LinkList<T>::LinkList(T a[], int n){ first=new Node<T>; Node<T> *r=first; for(int i=0;i<n;i++) { Node<T> *s=new Node<T>; s->data=a[i]; r->next=s; r=s; } r->next=NULL;}template<class T>T LinkList<T>::Delete(int i){ Node<T> *p=first; int count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL||p->next==NULL) throw "位置"; else{ Node<T> *q=p->next; double x=q->data; p->next=q->next; delete q; return x; }}template<class T>LinkList<T>::~LinkList(){ while(first!=NULL) { Node<T> *q=first; first=first->next; delete q; }}template<class T>void LinkList<T>::Insert(int i,T x){ Node<T> *p=first; int count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p==NULL) throw "位置"; else{ Node<T>*s; double x; s=new Node<T>; s->data=x; s->next=p->next; p->next=s; }}template<class T>void LinkList<T>::PrintList(){ Node<T> *p=new Node<T>; p=first->next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; }}void main(){ double a[]={1.1,2.2,3.3}; LinkList<double> test(a,3); cout<<"链表的初始状态为:"<<endl; test.PrintList(); cout<<endl<<"在第2个位置插入4.4后为:"<<endl; test.Insert(2,4.4); test.PrintList(); cout<<endl<<"在第3个位置删除元素后为:"<<endl; test.Delete(3); test.PrintList(); cout<<endl<<"在第10个位置插入5.5后为:"<<endl; test.Insert(10,5.5); test.PrintList(); cout<<endl<<"在第7个位置删除元素后为:"<<endl; test.Delete(7); test.PrintList(); getchar();}
展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询