C语言链表的操作实现

研究学习了好久才写出来,我是真的菜。

#include <stdio.h>
#include <stdlib.h>
//typedef struct Node* LList;
struct Node {
	int data;
	struct Node* next;
};

//初始化节点
void init(struct Node** phead) {
	*phead = NULL;
}

//求表长
int  getLength(struct Node* head) {
	int len = 0;
	while (head) {
		len++;
		head = head->next;
	}
	return len;
}
//输出链表
void printList(struct Node* head) {
	while (head) {
		printf("%d,", head->data);
		head = head->next;
	}
	putchar('\n');
}
//根据输入值x创建节点
struct Node* createNode(int x) {
	struct Node* t;
	t = (struct Node*)malloc(sizeof(struct Node));
	t->next = NULL;
	t->data = x;
	return t;
}
//找第K个元素的值
struct Node* findKth(struct Node* head, int k) {
	int count = 0;
	struct Node* p;
	p = head;
	while (p && count < k-1) {
		p = p->next;
		count++;
	}
	return p;
}
//插入
int insert(struct Node** phead, int k, int x) {
	if (k < 1) {
		return 0;
	}
	else if (k == 1) {
		struct Node* t;
		t = createNode(x);
		t->next = *phead;
		*phead = t;
		return 1;
	}
	else {
		struct Node* p;
		p = findKth(*phead, k - 1);
		if (p) {
			struct Node* t;
			t = createNode(x);
			t->next = p->next;
			p->next = t;
			return 1;
		}
		else {
			return 0;
		}
	}
}
//删除
int delete (struct Node** phead, int k, int* px) {
	if (k < 1) {
		return 0;
	}
	else if (k == 1) {
		if (*phead) {
			*px = (*phead)->data;
			*phead = (*phead)->next;
			return 1;
		}
		else return 0;
	}
	else {
		struct Node* p;
		p = findKth(*phead, k - 1);
		if (p == NULL || p->next == NULL) {
			return 0;
		}
		struct Node* t;
		t = p->next;
		p -> next = t->next;
		*px = t->data;
		free(t);
		return 1;
	}
}
int main(int argc, const char* argv[])
{
	struct Node* head;
	init(&head);        //初始化链表,改变链表,传指针
	//int k = getLength(head);    //求表长,不改变链表
	//printList(head);
	//printf("%d\n", k);
	insert(&head, 1, 11);
	//insert(&head, 1, 22);
	//insert(&head, 2, 33);
	//insert(&head, 4, 44);
	//insert(&head, 6, 55);
	printList(head);
	int x;
	delete(&head, 2, &x);
	printf("%d\n", x);
	printList(head);
	/*delete(&head, 2, &x);
	printf("%d\n", x);
	printlist(head);
	delete(&head, 2, &x);
	printf("%d\n", x);
	printlist(head);*/
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值