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