算法通关村第一关——链表青铜挑战笔记

小白也能学会的链表(C语言)

链表的定义
链表的基本操作

总结

链表的定义

typedef struct link{
	int val;
	struct link* next;
}Link

链表的基本操作

struct ListNode* insertNode(
struct ListNode* head, struct ListNode* nodeInsert, int position) {
 	if (head == NULL) {
		 return nodeInsert;
	 }
	 int size = getLength(head);
	 if (position > size + 1 || position < 1) {
		 printf("位置参数越界");
		 return head;
	 }
 // 插入节点到头部
	 if (position == 1) {
		 nodeInsert->next = head;
		 head = nodeInsert;
		 return head;
	 }
	 struct ListNode* pNode = head;
	 int count = 1;
	 while (count < position - 1) {
		 pNode = pNode->next;
		 count++;
	 }
	 nodeInsert->next = pNode->next;
	 pNode->next = nodeInsert;
	 return head;
}

删除与插入的操作大同小异,不再列举

//查找元素
ListNode* findNode(struct ListNode* p,int val){
	struct ListNode* temp = p;
	while(temp&&temp->val!=val){
		temp = temp->next;
	}
	if(temp && temp->val == val){
	return(temp);
	}
	else{
		return null;
	}
}
//打印链表
void printList(struct ListNode* p) {
 struct ListNode* temp = p;//temp指针用来遍历链表
 //只要temp指向结点的next值不是NULL,就执行输出语句。
 while (temp) {
 // struct ListNode* f = temp;//准备释放链表中的结点
 printf("%d ", temp->val);
 temp = temp->next;
 // free(f);
 }
 printf("\n");
}
//获取链表的长度
int32_t getLength(struct ListNode* p) {
 struct ListNode* temp = p;//temp指针用来遍历链表
 int length=0;
 //只要temp指向结点的next值不是NULL,就执行输出语句。
 while (temp) {
 // struct ListNode* f = temp;//准备释放链表中的结点
 length++;
 temp = temp->next;
 // free(f);
 }
 return length;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值