编程实现单链表基本操作,例如,创建结构,插入结点,删除结点等等。

算法设计:编程实现单链表基本操作,例如,创建结构,插入结点,删除结点等等。

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;

#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define TRUE 1;
#define FALSE 0;
#define OK 1;
#define ERROR 0;
#define INFEASIBLE - 1;

typedef int Status;
typedef int ElemType;
typedef struct LList {
	ElemType elem;
	struct LList* next;
}LList;

LList InitList_L(int size) {
	LList *head=NULL;
	LList *p = (LList*)malloc(sizeof(LList));
	head = p;
	p->elem = 0;
	p->next = NULL;
	for (int i = 0; i < size; i++) {
		LList* temp = (LList*)malloc(sizeof(LList));
		p->next = temp;
		p = temp;
		p->elem = i + 1;
		p->next = NULL;
	}
	return *head;
}

Status GetElem_L(LList& L, int loc, ElemType& e) {
	int i;
	LList *temp=&L;
	for (i = 1; i < loc; i++) {
		temp = temp->next;
	}
	e = temp->elem;
	return OK;

}

LList ListDelete_L(LList& L, int loc, ElemType& e) {
	int i;
	LList* temp = &L;
	LList* head = &L;
	if (loc == 1) {
		head = L.next;
		free(temp);
		return *head;
	}
	for (i = 1; i < loc-1; i++) {
		temp = temp->next;
	}
	LList* p = temp->next;
	temp->next = p->next;
	e = p->elem;
	free(p);
	return *head;
}

LList InsertElem_L(LList& L, int loc, ElemType e) {
	int i;
	LList* temp = &L;
	LList* head = &L;
	LList* p = (LList*)malloc(sizeof(LList));
	p->elem = e;
	if (loc == 1) {
		head = p;
		p->next = temp;
		return *head;
	}
	for (i = 1; i < loc - 2; i++) {
		temp = temp->next;
	}
	p->next = temp->next;
	temp->next = p;
	return *head;
}

Status Print_L(LList& L) {
	LList* temp = &L;
	cout << "out the table:";
	while (!(temp->next == NULL)) {
		cout << temp->elem << ' ';
		temp = temp->next;
	}
	cout << endl;
	return OK;

}

int main() {
	LList A;
	A.elem = 0;
	A.next = NULL;
	ElemType i;
	A = InitList_L(10);
	cout << "first table\n";
	Print_L(A);
	A = ListDelete_L(A, 5, i);
	cout << "del the num " << i << " so the table is:\n";
	Print_L(A);
	A = InsertElem_L(A, 5, i+2);
	cout << "add the num " << i+2 << " so the table is:\n";
	Print_L(A);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呆呆水獭_(:_」∠)_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值