2012年408的算法题

0 结果

1 题目

在这里插入图片描述
在这里插入图片描述

2 思路

  • 1 分别求两个链表的长度(len1,len2)
  • 2 用指针p指向长的链表的表头,接着让p指向和短的链表相同长度的前一个结点【假设len1>len2,就让p不断指向下一个结点len1-len2次】
  • 3 用q指向短的链表的表头,分别比较p->next和q->next是否相同(指针地址是否相同),如果相同则返回,否则,直到条件p->next为空,返回空结点。

3 实现

#include <cstdio>
#include <cstdlib>
#include <string.h>
typedef struct node{
    char data;
    struct node* next;
}NODE;

NODE* func(NODE* str1, NODE* str2){
    NODE *p = str1, *q = str2;
    int len1 = 0, len2 = 0;
    while(p != NULL){//求长度
        p = p->next;
        len1++;
    }
    while(q != NULL){
        q = q->next;
        len2++;
    }
    p = str1;
    q = str2;
    if(len1 > len2){
        int dis = len1 - len2;
        while (dis--){
            p = p->next;
        }
    }else{
        int dis = len2 - len1;
        while (dis--){
            q = q->next;
        }
    }
    while(p->next != q->next && p->next != NULL){
        p = p->next;
        q = q->next;
    }
    return  p->next;
    //while(p->next != NULL){
        //if(p->next == q->next){
          //  return p->next;
        //}else{
         //   p = p->next;
       //     q = q->next;
     //   }
   // }
 //   return  NULL;
}


//使用尾插法创建结点
void create(NODE* &L1, NODE* &L2){
    NODE *r1 = L1, *r2 = L2, *p;
    int num;
    char word1[] = "loading";
    char word2[] = "being";
    for(int i = 0;i < strlen(word1);i++){
        NODE *s = (NODE*)malloc(sizeof(NODE));
        s->data = *(word1 + i);
        r1->next = s;
        r1 = s;
    }
    r1->next = NULL;
    p = L1;
    while(p->next != NULL){
        p = p->next;
        if(p->data == 'i') break;
    }
    for(int i = 0;i < sizeof(word2) - 1;i++){
        NODE *s = (NODE*)malloc(sizeof(NODE));
        s->data = *(word2 + i);
        if(s->data == 'i'){
            r2->next = p;
            break;
        }
        r2->next = s;
        r2 = s;
    }
}
//打印数据
void print(NODE* L){
    NODE* p = L;
    while(p!=NULL){
        printf("%c", p->data);
        p = p->next;
    }
}

int main(){
    NODE *str1, *str2;
    str1 = (NODE*)malloc(sizeof(NODE));
    str1->next = NULL;
    str2 = (NODE*)malloc(sizeof(NODE));
    str2->next = NULL;
    create(str1, str2);
    NODE* s = func(str1, str2);
    //printf("%c", s->data);
    print(s);
    return  0;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页