careercup-链表 2.1
生活随笔
收集整理的這篇文章主要介紹了
careercup-链表 2.1
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2.1 編寫代碼,移除未排序鏈表中的重復節點。
不使用臨時緩存:
如果不允許使用臨時的緩存(即不能使用額外的存儲空間),那需要兩個指針, 當第一個指針指向某個元素時,第二個指針把該元素后面與它相同的元素刪除, 時間復雜度O(n2?)。
C++實現代碼:
#include<iostream> #include<new> using namespace std;struct ListNode {int val;ListNode *next;ListNode(int x):val(x),next(NULL) {} };void createList(ListNode *&L) {int arr[10]= {1,2,3,2,5,6,7,3,9,1};int i;ListNode *p=NULL;for(i=0; i<10; i++){ListNode *tmp=new ListNode(arr[i]);if(L==NULL){L=tmp;p=tmp;}else{p->next=tmp;p=tmp;}} }void deleteDup(ListNode *L) {if(L==NULL)return;ListNode *p=L;ListNode *q=NULL;while(p){q=p;while(q->next){if(q->next->val==p->val)q->next=q->next->next;elseq=q->next;}p=p->next;} }int main() {ListNode *head=NULL;createList(head);ListNode *p=head;while(p){cout<<p->val<<" ";p=p->next;}cout<<endl;deleteDup(head);p=head;while(p){cout<<p->val<<" ";p=p->next;}cout<<endl; }運行結果:
轉載于:https://www.cnblogs.com/wuchanming/p/4141163.html
總結
以上是生活随笔為你收集整理的careercup-链表 2.1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【java/C# 服务器】IOS 配置推
- 下一篇: Android-----Activity