龙空技术网

链表(2)

爱相随不后悔1 167

前言:

目前朋友们对“c语言链表排序的样例”都比较珍视,兄弟们都想要剖析一些“c语言链表排序的样例”的相关文章。那么小编同时在网摘上汇集了一些关于“c语言链表排序的样例””的相关资讯,希望咱们能喜欢,各位老铁们快快来了解一下吧!

链表练习记录:

237. 删除链表中的节点力扣

输入:head = [2,3,1,9], node = 1输出:[2,3,9]

83. 删除排序链表中的重复元素力扣

输入:head = [3,3,1,2,2]输出:[3,1,2]

思路:

237题思路:一般删除节点的做法是找到待删除节点的前一个节点。本题有个条件是无法访问链表的头节点 head ,只能直接访问要被删除的节点 。所以可以将待删除的节点后面一个节点的值赋值给当前要删除的节点,然后将待删除节点后面一个节点删除

83题思路:双指针,一前一后的两个指针,first,second,初始化为:first = head;second = head->next;当后面指针指向结构体的值与前面一个指针指向结构体元素的值相等(second->val == fisrt-val),就让second一直往后遍历,直到second->val != fisrt-val时,将first的下一个节点置为second(first->next = second),然后两个指针都往后移动一个节点,结束条件为second遍历结束(second == NULL)

代码实现:

237. 删除链表中的节点

#include<stdio.h>/*** Definition for singly-linked list.* struct ListNode {*     int val;*     struct ListNode *next;* };*/struct  ListNode {	int val;	struct ListNode *next;};void deleteNode(struct ListNode* node) {	node->val = node->next->val;	node->next = node->next->next;}int main(){	struct  ListNode node3;	node3.val = 3;	node3.next = NULL;	struct  ListNode node2;	node2.val = 2;	node2.next = &node3;	struct  ListNode  node1;	node1.val = 1;	node1.next = &node2;	deleteNode(& node1);	struct ListNode* result = &node1;	while (result != NULL)	{		printf("val = %d", result->val);		result = result->next;	}	return 0;}

237. 删除链表中的节点

83. 删除排序链表中的重复元素

#include<stdio.h>/*** Definition for singly-linked list.* struct ListNode {*     int val;*     struct ListNode *next;* };*/struct  ListNode {	int val;	struct ListNode *next;};struct ListNode* deleteDuplicates(struct ListNode* head) {	if (head == NULL)	{		return NULL;	}	struct ListNode* first = head;	struct ListNode* second = head->next;	while (second != NULL)	{		while ((second != NULL) &&(first->val) == (second->val) )		{			second = second->next;		}		first->next = second;		if (second != NULL)		{			second = second->next;			first = first->next;		}	}	return head;}int main(){	struct  ListNode node5;	node5.val = 3;	node5.next = NULL;	struct  ListNode node4;	node4.val = 3;	node4.next = &node5;	struct  ListNode node3;	node3.val = 2;	node3.next = &node4;	struct  ListNode node2;	node2.val = 1;	node2.next = &node3;	struct  ListNode  node1;	node1.val = 1;	node1.next = &node2;	struct ListNode* result =  deleteDuplicates(&node1);	while (result != NULL)	{		printf("val = %d", result->val);		result = result->next;	}	return 0;}

83. 删除排序链表中的重复元素

标签: #c语言链表排序的样例