Code19は、ソートされたリスト内の重複する要素を削除します

トピック

Leetcode83。
ソートさたリンクリスト内の重複要素を削除するソートされたリンクリストを指定して、すべての重複要素を削除し、各要素が1回だけ表示されるようにします。

例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

おすすめ

転載: blog.csdn.net/luoshabugui/article/details/109728459