LinkList:
#include<iostream> using namespace std; typedef int elemType; typedef struct Node { elemType data; Node *next; }*LinkList; bool InitList(LinkList *L)//初始化 { *L = new Node; if(!L) return false; (*L)->next = NULL; return true; } bool IsEmpty(LinkList L) { if(L->next==NULL) return false; else return true; } bool ClearList(LinkList *L) { cout<<"Clear List."<<endl; LinkList p,q; p = (*L)->next; if(!p) return true; while(p) { q = p->next; delete p; p=q; } (*L)->next = NULL; return true; } int LengthList(LinkList *L) { //cout<<"The length of list is:"; LinkList p; p = (*L)->next; int i=0; while(p) { p=p->next; i++; } return i; } bool GetElem(LinkList *L, int pos, elemType *pd) { cout<<"Get the "<< pos <<"th item:"; LinkList p; p = (*L)->next; int i=1; while(p && i<pos) { p = p->next; i++; } if(!p || i>pos) return false; *pd = p->data; return true; } //在L中第pos个结点位置之前插入新数据元素x bool InsertList(LinkList *L, int pos, elemType x) { LinkList p,q; int i=1; p = *L; while(p && i<pos) { p = p->next; i++; } if(!p || i>pos) return false; q = new Node; q->data = x; q->next = p->next; p->next = q; return true; } bool DeleteList(LinkList *L, int pos, elemType *y) { int i =1; LinkList p,q; p = *L; while(p->next && i<pos) { p = p->next; i++; } if(!(p->next) || i>pos) return false; q = p->next; *y = q->data; p->next = q->next; delete q; return true; } int Locate(LinkList *L,elemType z) { int i=1; LinkList p; p = (*L)->next; while(p && p->data!= z) { p = p->next; i++; } if(!p) return 0; return i; } void PrintList(LinkList *L) { LinkList p; p = (*L)->next; int i=1; while(p) { cout << i << ":\t"<< p->data <<endl; p = p->next; i++; } } LinkList *Reverse(LinkList *L)//反转单链表 { cout<<"Reverse List:"<<endl; LinkList p,q,s; if((*L)->next->next==NULL || (*L)->next==NULL) return L; p = (*L)->next; q = p->next; (*L)->next->next = NULL; while(q) { s = q->next; q->next = p; p = q; q = s; } (*L)->next = p; return L; } int main() { LinkList L; InitList(&L); for(int i=1;i<7;i++) InsertList(&L,i,i); PrintList(&L); cout<<endl; int x = Locate(&L,2); cout<<"the location of 2 is: "<< x << endl; cout<<endl; cout<<"after delete the 6th item:"<<endl; int num; DeleteList(&L,6,&num); PrintList(&L); cout<<endl; Reverse(&L); PrintList(&L); cout<<endl; return 0; }
时间: 2024-12-15 06:58:12