【力扣习题】C语言
目录
【876.链表的中间点】
思路:
1、计算链表的长度
2、遍历到链表中间长度并输出值
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* middleNode(struct ListNode* head) {
int n = 1;
struct ListNode* p = malloc(sizeof(struct ListNode));
p->next = NULL;
p->val = head->val;
p = head;
while(p->next != NULL)
{
p = p->next;
n++;
}
if(n==1)
{
return head;
}
int k = n/2;
struct ListNode *q = head;
while(k--)
{
q = q->next;
}
printf("%d\n",q->val);
head = q;
return head;
}
【83删除排序链表中的重复元素】
思想:
1、如果链表为空,返回NULL
2、遍历判断是否相等,相等跳过
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head) {
if(head==NULL)
{
return NULL;
}
struct ListNode* p = malloc(sizeof(struct ListNode));
p->next = NULL;
p->val = head->val;
p = head;
while(p->next)
{
if(p->val == p->next->val)
{
p->next = p->next->next;
}
else
{
p= p->next;
}
}
return head;
}
原文地址:https://blog.csdn.net/m0_65146517/article/details/140647418
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!