C语言单链表

# include <stdio.h> 
# include <stdlib.h>

typedef struct LNode{
	int data;
	struct LNode *next;
}Node,*NodeList;

void InitList(NodeList &L) {
	L = (Node *)malloc(sizeof(Node));
	L->next == NULL;
}

void addList(NodeList &L, int k) {
	Node *end = L;
	for (int i=0;i<k;i++) {
		Node *aa = (Node *)malloc(sizeof(Node));
		aa->data = i;
		aa->next = NULL;
		end->next = aa;
		end = aa;
	}
}

int Length(NodeList &L) {
	Node *head = L->next;
	int cc = 0;
	while(head!=NULL) {
		head = head->next;
		cc++;
	}
	return cc;
}

bool writeList(NodeList &L, int k, int e) {
	Node *head = L->next;
	int length = Length(L);
	if ((k<1)||(k>length+1)) {
		return false;
	}else {
		Node *cc = (Node *)malloc(sizeof(Node));
		cc->data = e;
		if (k==1) {
			cc->next = head;
			L->next = cc;
			return true;			
		}else {
			for (int i=0;i<k-2;i++) {
				head = head->next;
			}
			cc->next = head->next;
			head->next = cc;
			return true;
		}
	}
}

bool DeleteList(NodeList &L, int k, int &e) {
	int ll = Length(L);
	Node *head = L->next;
	if ((k<1)||(k>ll)) {
		return false;
	}else {
		if (k==1) {
			L->next = head->next;
			e = head->data;
			free(head);
			return true;
		}
		for (int i=0;i<k-2;i++) {
			head = head->next;
		}
		Node *c = head->next;
		e = head->next->data;
		head->next = head->next->next;
		free(c);
		return true;
	}
} 




void outputList(NodeList &L) {
	Node *head = L->next;
	int ll = Length(L);
	while(head!=NULL) {
		int kk = head->data;
		printf("%d - > ", kk);
		head = head->next;
	}
	printf("\n长度: %d\n", ll);
} 

int main() {
	NodeList L;
	InitList(L);
	addList(L, 10);
	outputList(L);
	if (writeList(L, 1, 999)) {
		printf("\n插入成功\n");
	}else {
		printf("\n插入失败\n");
	}
	outputList(L);
	int e = -1;
	if (DeleteList(L, 1, e)) {
		printf("\n删除成功元素:%d\n", e);
	}else {
		printf("\n删除失败\n");
	}
	outputList(L);
}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值