|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目大意是处理两个链表取交集;
我遇到的问题主要在于主函数的while循环,不知道为什么不正常跳出
输入样例:
1 2 5 -1
2 4 5 8 10 -1
输出样例:
2 5
- #include<stdio.h>
- #include<stdlib.h>
- typedef struct M{
- int num;
- struct M *next;
- }M ;
- M *head,*tail;
- M *node()
- {
- head=tail=NULL;
- M*p=head;
- p=(M*)malloc(sizeof(M));
- scanf("%d",&p->num);
- while(p->num>0)
- {
- if(head==NULL)
- head=p;
- else
- tail->next=p;
- tail=p;
- tail->next==NULL;
- p=(M*)malloc(sizeof(M));
- scanf("%d",&p->num);
-
- }
- return head;
- }
- int main()
- {
- M *p,*q,*s3;
- p=node();
- q=node();
- head=tail=s3=NULL;
- int sum=0;
-
- while((p!=NULL)&&(q!=NULL))//就是这个位置,不知为什么最后链表结束后不正常跳出还会打印出地址。
- {
- if((p->num)<(q->num))
- {
- p=p->next;
- }
- else if(p->num>q->num)
- {
- q=q->next;
- }
- else if(p->num==q->num)
- {
- s3=(M*)malloc(sizeof(M));
- s3->num=q->num;
- if(head==NULL)
- head=s3;
- else
- tail->next=s3;
- tail=s3;
- s3->next=NULL;
- p=p->next;
- q=q->next;
- sum++;
- }
- }
- printf("%d",head->num);
- head=head->next;
- for(;head!=NULL;head=head->next)
- printf(" %d",head->num);
- }
复制代码
我的输出
本帖最后由 jackz007 于 2019-4-28 10:24 编辑
代码过于复杂,简单修改了一下,请楼主参考 - #include<stdio.h>
- #include<stdlib.h>
- typedef struct M{
- int num ;
- struct M * next ;
- } node ;
- node * link()
- {
- node * p1 , * p2 , * head ;
- int num ;
- head = NULL ;
- for(;;) {
- scanf("%d" , & num) ;
- if(num >= 0) {
- if((p2 = (node *) malloc(sizeof(node))) != NULL) {
- p2 -> num = num ;
- p2 -> next = NULL ;
- if(head == NULL) head = p2 ;
- else p1 -> next = p2 ;
- p1 = p2 ;
- } else {
- fprintf(stderr , "error: failure of malloc()\n") ;
- head = NULL ;
- break ;
- }
- } else {
- break ;
- }
- }
- return head ;
- }
- int main()
- {
- node * ph , * p , * qh , * q ;
- int c ;
- ph = link() ;
- qh = link() ;
- c = 0 ;
- for(p = ph ; p != NULL ; p = p -> next) {
- for(q = qh ; q != NULL ; q = q -> next) {
- if (p -> num == q -> num) {
- if(c) printf(" ") ;
- printf("%d" , p -> num) ;
- c ++ ;
- }
- }
- }
- if(! c) printf("no match data found!\n") ;
- free(ph) ;
- free(qh) ;
- }
复制代码
|
|