careercup-链表 2.1
生活随笔
收集整理的這篇文章主要介紹了
careercup-链表 2.1
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
2.1 編寫(xiě)代碼,移除未排序鏈表中的重復(fù)節(jié)點(diǎn)。
不使用臨時(shí)緩存:
如果不允許使用臨時(shí)的緩存(即不能使用額外的存儲(chǔ)空間),那需要兩個(gè)指針, 當(dāng)?shù)谝粋€(gè)指針指向某個(gè)元素時(shí),第二個(gè)指針把該元素后面與它相同的元素刪除, 時(shí)間復(fù)雜度O(n2?)。
C++實(shí)現(xiàn)代碼:
#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; }運(yùn)行結(jié)果:
轉(zhuǎn)載于:https://www.cnblogs.com/wuchanming/p/4141163.html
總結(jié)
以上是生活随笔為你收集整理的careercup-链表 2.1的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【java/C# 服务器】IOS 配置推
- 下一篇: MySql项目中使用的小窍门