10.練習
統計單向鍊錶的每個元素出現的次數
#include
#include
#define n 11
typedef struct node
elemsn;
elemsn * createlink(int a);
void printlink(elemsn *h);
int main()
;//建立
head = createlink(a);
//列印
printlink(head);
printf("\n");
return 0;
}elemsn * createlink(int a)
else
}else
}return h;
}void printlink(elemsn *h)
}判斷是否出現交叉
#include
#include
#define n 8
typedef struct node
elemsn;
elemsn * createlink1(int a);//建立
void printlink(elemsn *h);//列印
elemsn * mixnode(elemsn *h1,elemsn *h2);//判斷是否有交叉點
int main()
;int i =0;
//建立
head = createlink1(a);
//列印原鍊錶
printlink(head);
printf("\n");
//將原鍊錶變成交叉鍊錶
p = head; //頭結點是3,p指向3
head = head->next; //將head後移1個,變成head指向6
for(q = head;i < 3;q = q->next,i++); //現在 q 在 4 上指著呢
p->next = q->next; //把 7 也變成了 3 的後繼
head1 = head; //鍊錶1是 6,5,8,4,7,2,1
head2 = p; //鍊錶2是 3,7,2,1
//判斷是否有交叉點
head = mixnode(head1,head2);
printf("第乙個交叉點是:%d\n",head->data);
return 0;
}elemsn * createlink1(int a)
return head;
}void printlink(elemsn *h)
}//判斷是否有交叉點
elemsn * mixnode(elemsn *h1,elemsn *h2)
if(n1 == -1)
else if(n2 == -1)
else
}方法2(最優,時間複雜度o(n),空間複雜度o(1))
#include
#include
#define n 8
typedef struct node
elemsn;
elemsn * createlink1(int a);//建立
void printlink(elemsn *h);//列印
elemsn * mixnode(elemsn *h1,elemsn *h2);//判斷是否有交叉點
int main()
;int i =0;
//建立
head = createlink1(a);
//列印原鍊錶
printlink(head);
printf("\n");
//將原鍊錶變成交叉鍊錶
p = head; //頭結點是3,p指向3
head = head->next; //將head後移1個,變成head指向6
for(q = head;i < 3;q = q->next,i++); //現在 q 在 4 上指著呢
p->next = q->next; //把 7 也變成了 3 的後繼
head1 = head; //鍊錶1是 6,5,8,4,7,2,1
head2 = p; //鍊錶2是 3,4,7,2,1
//判斷是否有交叉點
head = mixnode(head1,head2);
printf("第乙個交叉點是:%d\n",head->data);
return 0;
}elemsn * createlink1(int a)
return head;
}void printlink(elemsn *h)
}//判斷是否有交叉點
elemsn * mixnode(elemsn *h1,elemsn *h2)
for(p1 = h1;n;p1 = p1->next,n--);//先讓長鍊錶指標h1跳 n 個結點
for(p2 = h2;p1 != p2;p1 = p1->next,p2 = p2->next); //同步跳,直到相等時就是第乙個交叉鍊錶
return p1; //返回p1和p2是一樣的,因為p1和p2此時指向的是同乙個結點
}
C語言資料結構之鍊錶部分(2)
2.鍊錶的一些練習 1 輸出尾結點元素 include include define n 5 typedef struct node elemsn elemsn createlink1 int a void printlink elemsn h int main elemsn head null h...
C語言資料結構之鍊錶部分(11)
11.建立單向迴圈鍊錶 include include typedef struct node elemsn elemsn createlink int a,int n void printlink elemsn h elemsn delkeynode elemsn h,int key int ma...
C 語言 資料結構之雙向鍊錶
雙向鍊錶的空間結構如下圖所示 int initdlist dlinklist head 初始化雙向迴圈鍊錶 int createdlist dlinklist head,int n 建立雙向迴圈鍊錶 return 1 void printdlist dlinklist head 輸出雙向迴圈鍊錶中的...