目录
【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;
}