在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/C/ leetcode上的算法題報錯Submission Result: Time L

leetcode上的算法題報錯Submission Result: Time Limit Exceeded

leet算法題第二題,兩個數(shù)字相加,通過鏈表的形式相加。

題目如下:

  • 英文:You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.You may assume the two numbers do not contain any leading zero, except the number 0 itself.
  • 中文:給你兩個非空鏈表,表示兩個非負整數(shù)。數(shù)字以相反的順序存儲,每個節(jié)點包含一個數(shù)字。添加這兩個數(shù)字并將其作為鏈接列表返回。 您可以假定這兩個數(shù)字不包含任何前導零,除了數(shù)字0本身。

我的源碼:

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    struct ListNode *t1,*t2,*new,*head,*hh;
    t1 = l1;
    t2 = l2;
    int jinwei = 0;
    new = malloc(sizeof(struct ListNode));
    new->next = NULL;
    head=new;
    hh = head;
    
    while(t1 && t2){
        new->val = t1->val + t2->val + jinwei;
        jinwei = new->val /10 ;
        new->val = new->val %10;
        t1 = t1->next;
        t2 = t2->next;
        new->next = head->next;
        head->next = new;
        head = head->next;
        new = malloc(sizeof(struct ListNode));
    }
    if(t1==NULL && t2==NULL){
        
        new->val = jinwei;
        new->next = head->next;
        head->next = new;
        head = head->next;
    }
    else if(t2 != NULL ){
        new = t2+jinwei;
    }
    else{
        new = t1+jinwei;
    }
    return hh;
}

leetcode報錯:
圖片描述

回答
編輯回答
執(zhí)念
    new->next = head->next;
    head->next = new;
    head = head->next;
    new = malloc(sizeof(struct ListNode));

運行中,此四行構造出一循環(huán)鏈表。故addTwoNumbers函數(shù)退出后,判定程序在打印結果時死循環(huán)。

2017年10月3日 12:53