Ch2-1: de-duplicate a linked-list with/without additional buffer

Chap 2 deal with linked-list. So I finished Xuetang

Ch2-1:

The different is the time complexity and the reason we use 2 poniters/3 pointers:

p is the base addr, q is the increased pointer;

c is the base-base addr, p is the base-increase pointer, q is the increased pointer.

//http://hawstein.com/posts/2.1.html
//http://en.cppreference.com/w/cpp/utility/hash

#include 
   
   
    
    
#include 
    
    
     
     
using namespace std;

struct node{
    int data;
    node *next;
};
bool hass[100];

node* init(int* a, int n){
    node *head, *p;
    for(int i=0; i
     
     
      
      data = a[i];
        if(i==0){
            head = p = nd;
            continue;
        }
        p->next = nd;
        p = nd;
    }
    return head;
}

void print(node *head){
    node* p;
    p = head;
    while(p){
        cout<
      
      
       
       data<<"_ ";
        p = p->next;
    }
    cout<< "ty" << endl;
}

void removedulicate(node *head){  // with buffer hass[100]--O[n]
    if(head==NULL) return;
    node *p=head, *q=head->next;
    hass[head->data] = true;
    while(q){
        if(hass[q->data]){
            node *t = q;
            p->next = q->next;
            q = p->next;
            delete t;
        }
        else{
            hass[q->data] = true;
            p = q; q = q->next;
        }
    }
}
void removedulicate1(node *head){  //without buffer  -- O[n^2]
    if(head==NULL) return;
    node *p, *q, *c=head;
    while(c){
        p=c; q=c->next;
        int d = c->data;
        while(q){
            if(q->data==d){
                node *t = q;
                p->next = q->next;
                q = q->next;
                delete t;
            }
            else{
                p = q; q = q->next;
            }
        }
        c = c->next;
    }
}

int main(){
    int n = 10;
    int a[] = {
        3, 2, 1, 3, 5, 6, 2, 6, 3, 1 
    };
    memset(hass, false, sizeof(hass));
    node *head = init(a, n);
    cout << head << " jg " << head->data <
       
       
      
      
     
     
    
    
   
   

如果在init 里面的最后两句这样改的话
p = p->next;
p = nd;
输出只有head
Executing the program....
$demo 
0x602010 jg 3
3_ ty
3_ ty

因为这样只是把p的后继指回给p,而不是更新。
正确的做法是:
p->next = nd; //将p的后继更新为new node;
p= nd; // 讲p(即地址)更新为这个new node。


Here is the output:
Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo 
0x602010 jg 3
3_ 2_ 1_ 3_ 5_ 6_ 2_ 6_ 3_ 1_ ty
3_ 2_ 1_ 5_ 6_ ty



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值