Remove Duplicates from Sorted List II--LeetCode,removeduplicates

來源:互聯網
上載者:User

Remove Duplicates from Sorted List II--LeetCode,removeduplicates
題目:

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

思路:先鎖定頭,然後處理中間位置,記得最後處理尾部,知識繁瑣,處理頭部時,找到一個節點,當前節點沒有相同的連續節點,同時節點和後序節點不同。處理中間只需要記錄前序節點和遍曆節點即可,使得遍曆節點沒有連續相同的節點。如果有連續相同的節點,那麼刪除所有的連續相同的節點

#include <iostream>#include <vector>using namespace std;typedef struct list_node List;struct list_node{int value;struct list_node* next;};void Init_List(List*& head,int* array,int n)  {      head = NULL;      List* tmp;      List* record;      for(int i=1;i<=n;i++)      {          tmp = new List;          tmp->next = NULL;          tmp->value = array[i-1];          if(head == NULL)          {              head = tmp;              record = head;          }          else          {              record->next = tmp;              record = tmp;          }      }  }  void print_list(List* list)  {      List* tmp=list;      while(tmp != NULL)      {          cout<<tmp->value<<endl;          tmp = tmp->next;       }  }    void RemoveDuplicate(List*& head){if(head == NULL || head->next==NULL)return ; List* pre=head; List* cur; List* fast; if(head->value == head->next->value){ while(1) { while(pre != NULL &&pre->next != NULL) { if(pre->value == pre->next->value) pre = pre->next; else break; } pre = pre->next; if(pre->next == NULL || pre->value != pre->next->value) { head = pre; break; }  }}  if(head == NULL) return ; pre = head; cur=head->next; while(cur !=NULL && cur->next != NULL) { if(cur->value != cur->next->value) { if(pre->next != cur) // 不相鄰 {cur = cur->next; pre->next = cur;} else{pre = cur;cur = cur->next;}  } else { cur = cur->next; } }if(pre->next!=NULL && pre->next->next !=NULL){if(pre->next->value == pre->next->next->value)pre->next = NULL;}}   int main() {int array[]={1,1,1,2,2,3,4,4,4,5,5,7,7,8};List* head;Init_List(head,array,sizeof(array)/sizeof(int));RemoveDuplicate(head);print_list(head); return 0;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.