Code19 delete duplicate elements in the sorted list

topic

leetcode83. Delete duplicate elements in the
sorted linked list Given a sorted linked list, delete all duplicate elements so that each element appears only once.

Example 1:
Input: 1->1->2
Output: 1->2

Example 2:
Input: 1->1->2->3->3
Output: 1->2->3

Code

// 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;
}

test

// 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;
}
  • result
11233
123

Guess you like

Origin blog.csdn.net/luoshabugui/article/details/109728459