学习时间:
2023年1月21日
题目描述:
题解分享:
// 作 者 : 繁 华 倾 夏
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
// 力扣(LeetCode):83. 删除排序链表中的重复元素
//Definition for singly-linked list. 定义单链表
struct ListNode {
int val;
struct ListNode *next;
};
// head:单链表的头结点
struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode* n1 = head, * n2 = head; // 新建两个指针每回进行链表上元素的比较
if (!head) {
return head; // 判断head是否为空,为空则直接返回
}
while (n1->next) { // 利用n1遍历链表,注意此时要进行的是n1->next的遍历,不能遍历n1
n2 = n1->next; // 每次遍历n2都指向n1的下一个结点
if (n1->val == n2->val) { // 如果n1和n2的值相等
n1->next = n2->next; // 那么n1就指向n2的下一个结点,实现断链操作
}
else {
n1 = n1->next; // 不相等时,移动n1到下一个结点位置
}
}
return head;
}
// 从尾部插入数据
void SListPushBack(struct ListNode** pphead, int x) {
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->val = x;
newnode->next = NULL;
if (*pphead == NULL) {
*pphead = newnode;
}
else {
// 找到尾节点
struct ListNode* tail = *pphead;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = newnode;
}
}
// 打印链表
void SListPrint(struct ListNode* phead)
{
struct ListNode* cur = phead;
while (cur != NULL) {
printf("%d->", cur->val);
cur = cur->next;
}
printf("NULL\n");
}
// 测试用例
// 输入 head = [1, 1, 2]
// 输出 [1, 2]
int main() {
struct ListNode* head = NULL; // 建立空链表
SListPushBack(&head, 1); // 为链表插入数据
SListPushBack(&head, 1);
SListPushBack(&head, 2);
struct ListNode* re = deleteDuplicates(head);
SListPrint(re); // 打印链表
return 0;
}
【繁华倾夏】【每日力扣题解分享】【Day7】