連結清單在資料結構中占了很大比重,現在有必要寫一下關于單連結清單,雙向連結清單的建立,查詢,插入,删除,輸出,希望對你們有幫助!以下為代碼展示
// linklist.cpp : Defines the entry point for the console application.
//單連結清單與雙連結清單的操作,建立,插入,删除,查找
#include "stdafx.h"
#include <iostream>
#include <malloc.h>
#include <cstdio>
#include <string>
using namespace std;
//---單連結清單的存儲結構
typedef struct Lnode{
string Data;
struct Lnode *next;
}Lnode,*Linklist;
//---建一個連結清單
//--雙向連結清單結構
typedef struct DLnode{
string data;
struct DLnode *prior;
struct DLnode *next;
}DLnode,*DLinklist;
//---以下為單連結清單的操作
struct Lnode *create(int *countnode){//傳回的是節點指針
Lnode *head, *p, *q;
int i=0;
//---申請配置設定一個節點malloc()
p = (struct Lnode*)malloc(sizeof(Lnode));
cin >> p->Data;
p -> next = NULL;
while (p->Data!="")
{
if (head == NULL)
head = p;
else
q->next = p;
q = p;
}
(*countnode)++;
return head;
}
void show(struct Lnode *head){
struct Lnode *p;
if (head == NULL){
cout << "null" << endl;
return;
}
for (p = head; p != NULL; p = p->next){
cout << p->Data << "\n" << endl;
}
}
//--擷取第i個元素指針,查找
struct Lnode *GetElem(Linklist L, int i,int j, string &data){
struct Lnode *p;
p = L->next;
while (p&&j < i){
p = p->next;
++j;
}
if (!p || j>i)
return nullptr;
data = p->Data;
return p;
}
//---元素的插入
void Listinsert(Linklist &L, int i,int j, string data){
struct Lnode *p, *s;
p = L;
while (p&&j<i-1)
{
p = p->next;
++j;
}
if (!p || j>i - 1)
return;
s = (Linklist)malloc(sizeof(Lnode));
s->Data = data;
s->next = p->next;
p->next = s;
return;
}
//--元素的删除
void elemdelete(Linklist &l, int i,int j,string data){
struct Lnode *p,*q;
p = l;
//尋找第i個節點,并令p指向其前驅
while (p->next&&j<i-1){
p = p->next;
++j;
}
if (!p->next || j>i - 1)
return;
q = p->next;//這裡相當于p->next->next
p -> next = q->next;
data = q->Data;
free(q);
}
//---以下為雙向連結清單的操作
//---雙向連結清單的建立,采用尾插
DLinklist Dlinkcreat(struct DLnode *l, DLnode *p, DLnode *r){
l = (DLnode*)malloc(sizeof(DLnode));//---申請頭節點
l->next = NULL;
r = l;
r->next = NULL;
string s;
while (cin>>s)
{
p = (DLnode*)malloc(sizeof(DLnode));
p->data = s;
p->next = r->next;
r->next = p;
r = p;
}
r->next = NULL;
return l;
}
//--說明,一般的連結清單查詢操作與單連結清單相似,其實就是多了一個前驅的操作
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}