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

该博客介绍了如何使用C语言解决LeetCode中的第83题,即删除排序链表中的重复元素。通过设置快慢指针,遍历链表并比较相邻节点的值,当值相等时,删除重复节点。提供的代码实现了问题的解决方案,并通过了示例测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

leetcode83. 删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:
输入: 1->1->2
输出: 1->2

示例 2:
输入: 1->1->2->3->3
输出: 1->2->3

代码
// C 
// 思路:快慢指针
#include <malloc.h>
struct ListNode {
    int val;
    struct ListNode *next;
};

struct ListNode* deleteDuplicates(struct ListNode* head){
  if(NULL == head) {
    return head;
  }

  struct ListNode* ps = head; // 慢指针
  struct ListNode* pf = head->next; // 快指针
  while (NULL != pf) {
    if (pf->val == ps->val){
      struct ListNode* ptemp = pf;
      pf = pf->next;
      free(ptemp); // 释放资源
    }else{
      ps->next = pf;
      ps = ps->next;
      pf = pf->next;
    }
  }

  ps->next = NULL; // 注意这里,链表结尾处

  return head;
}
测试
// C++
#include <vector>
#include <iostream>
using namespace std;

// 创建链表
ListNode* create(vector<int> vc) {
  ListNode* head = nullptr;
  ListNode* tail = nullptr;
  auto it = vc.begin();
  while (it != vc.end()) {
    ListNode* temp = new ListNode();
    temp->val = *it;
    temp->next = nullptr;

    if (nullptr == tail) {
      head = temp;
      tail = temp;
    } else {
      tail->next = temp;
      tail = tail->next;
    }
    ++it;
  }
  return head;
}

// 释放链表
void del(ListNode* head) {
  while (head) {
    auto temp = head->next;
    delete head;
    head = temp;
  }
}

// 打印链表
void print(ListNode* head) {
  while (head) {
    cout << head->val;
    head = head->next;
  }
  cout << endl;
}

int main() {
  vector<int> vc1 = { 1, 1, 2, 3, 3 };
  auto l1 = create(vc1);
  print(l1);

  auto l2 = deleteDuplicates(l1);
  print(l2);

  del(l2);

  std::cin.get();
  return 0;
}
  • 结果
11233
123
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值