单链表,双向链表的插入,查询,创建,删除,输出

链表在数据结构中占了很大比重,现在有必要写一下关于单链表,双向链表的创建,查询,插入,删除,输出,希望对你们有帮助!以下为代码展示
// 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;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值