1. 程式人生 > >連結串列及其操作的實現

連結串列及其操作的實現

#include <iostream>
#include <cstdio>
#include <stdlib.h>
using namespace std;
typedef char ElemType;
typedef struct LNode
{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;
int ListLength(LinkList L);
ElemType GetElem(LinkList L,int i);
void InsertList(LinkList &
L,ElemType x,int i); int DeleteElem (LinkList &L,int i); void DisplayList(LinkList L); LinkList LA; int main() { LA=NULL; ElemType cs; int len=0; // scanf("%s",&LA); InsertList(LA,'a',1); InsertList(LA,'B',2); InsertList(LA,'C',2); cs=GetElem(LA,3); cout<<
cs<<endl; cout<<ListLength(LA)<<endl; DisplayList(LA); DeleteElem(LA,2); DisplayList(LA); return 0; } int ListLength(LinkList L) { //cout<<"ListLength"<<endl; int n=0; struct LNode *q=L; if(L==NULL) cout<<"連結串列為空"<<endl;
while(q!=NULL) { n++; q=q->next; } return n; } ElemType GetElem(LinkList L,int i) { //cout<<"GetElem"<<endl; int j=1; struct LNode *q=L; while(j<i&&q!=NULL) { q=q->next; j++; } if(q!=NULL) return (q->data); else cout<<"位置引數不正確!"<<endl; return 0; } void InsertList(LinkList &L,ElemType x,int i) { //cout<<"InsertList"<<endl; int j=1; struct LNode *s,*q; s=new LNode ; s->data=x; q=L; if(i==1) { s->next=q; L=s; } else { while(j<i-1&&q->next!=NULL) { q=q->next; j++; } if(j==i-1) { s->next=q->next; q->next=s; } } } int DeleteElem (LinkList &L,int i) { //cout<<"DeleteElem "<<endl; int j=1; struct LNode *q=L,*t; if(i==1) { t=q; q=q->next; } else { while(j<i-1&&q->next!=NULL) { j++; q=q->next; } if(q->next!=NULL&&j==i-1) { t=q->next; q->next=t->next; } else cout<<"位置引數不正確!"<<endl; } if(t) return t->data; return 0; } void DisplayList(LinkList L) { struct LNode *q; q=L; cout<<"連結串列元素"; if(q==NULL) cout<<"連結串列為空"<<endl; else if(q->next==NULL) cout<<q->data<<"."; else { while(q->next!=NULL) { cout<<q->data<<" "; q=q->next; } cout<<q->data<<" "; } cout<<endl; }