循环链表C/C++实现(数据结构严蔚敏版)
生活随笔
收集整理的這篇文章主要介紹了
循环链表C/C++实现(数据结构严蔚敏版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1頭文件LinkList.h:
#include<iostream> using namespace std; #include<malloc.h>#define error 0 #define ok 1 typedef int Status; typedef int ElemType;typedef struct LNode{ElemType data;struct LNode* prior;struct LNode* next;}LNode, *LinkList;//初始化循環鏈表 Status InitList(LinkList& L, int n);//銷毀一個帶頭結點的雙向循環鏈表,ok Status DestroyList(LinkList &L); // 打印循環鏈表信息 Status Print(const LinkList& L); //查詢雙向鏈表中的第i個數據 Status Select(const LinkList& L, int i, ElemType& e);//定位第i個位置的地址,,并返回給e Status Get(const LinkList& L, int i, LinkList& e);//在第i個位置插入信息 Status ListInsert(LinkList& L, int i, const ElemType& e); //刪除第i個位置的信息 Status ListDelete(LinkList& L, int i, ElemType& e);//定位值為e的結點的位置 Status LocateElem(const LinkList& L, ElemType e);2.源文件LinkList.cpp:
#include "LinkList.h"//初始化循環鏈表,正序創建節點 Status InitList(LinkList& L, int n){LinkList p, s;//中間變量 int i; L= new LNode(); p = L; cout<<"請輸入"<<n<<"個數據"<<endl;for(i=0;i<n;i++) { s = new LNode(); if(!s) exit(0);cin>>s->data;p->next = s; s->prior=p; p=s; } p->next=L; L->prior=p; return ok; }//銷毀雙向鏈表 Status DestroyList(LinkList &L)//銷毀一個帶頭結點的雙向循環鏈表,ok { //p接收下一個數據地址 LinkList p = NULL; while(L) { p=L->next; delete L; L=p; } } // 打印循環鏈表信息 Status Print(const LinkList& L){if(L->next == L && L->prior == L){cout<<"雙向鏈表為空"<<endl; }LinkList p = L->next;while(p != L){cout<<p->data<<" ";p = p->next;} cout<<endl; } //查詢雙向鏈表中的第i個數據,并返回給e Status Select(const LinkList& L, int i, ElemType& e){LinkList p = L->next;while(p != L && i > 1){i--;p = p->next;} e = p->data;return ok; }//在第i個位置插入數據信息 Status ListInsert(LinkList& L, int i, const ElemType& e){LinkList p, s;//先獲取第i個位置的地址,傳給p Get(L, i, p);if(!(s = new LNode())) return error;s->data = e;s->prior = p->prior;p->prior->next = s;s->next = p;p->prior = s;return ok;} //刪除第i個位置的信息 Status ListDelete(LinkList& L, int i, ElemType& e){LinkList p;Get(L, i, p);e = p->data;p->prior->next = p->next;p->next->prior = p->prior;delete p;return ok; } //定位第i個位置的地址,,并返回給e Status Get(const LinkList& L, int i, LinkList& s){LinkList p;p = L->next;while(p != L && i > 1){i--;p = p->next;}s = p;return ok; } //定位數據的位置 Status LocateElem(const LinkList& L, ElemType e) { LinkList p = NULL; p=L->next;int i = 0;;while(p!=L) { i++;if(e == p->data) return i; p=p->next; } cout<<"數據不存在"<<endl;return error; }3.測試文件test.cpp
#include <iostream> #include "LinkList.h"/* run this program using the console pauser or add your own getch, system("pause") or input loop */int main(int argc, char** argv) {LinkList L;ElemType e;int i, n;InitList(L, 3);cout<<"初始化完成"<<endl;Print(L);cout<<"請輸入刪除的位置"<<endl;cin>>i;ListDelete(L, i, e);Print(L);return 0; }總結
以上是生活随笔為你收集整理的循环链表C/C++实现(数据结构严蔚敏版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 单链表C/C++实现(数据结构严蔚敏)
- 下一篇: 栈C/C++实现(数据结构严蔚敏版)