题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pHead1 ListNode类 
 * @param pHead2 ListNode类 
 * @return ListNode类
 */
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    struct ListNode* temp1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* temp2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode) * 1001);

    temp1 = pHead1;
    temp2 = pHead2;

    struct ListNode* cur ;
    // result = cur;
    cur = result;
    while((temp1 != NULL) || (temp2 != NULL))
    {

        if((temp1 != NULL) && (temp2 != NULL))
        {

            if(temp1->val <= temp2->val)
            {
                printf("111  p1 %d  p2 %d  cur %d\n",temp1->val, temp2->val, cur->val);
                cur->next = temp1;
                cur = temp1;
                temp1 = temp1->next;
            } else {
                printf("222  p1 %d  p2 %d cur %d\n",temp1->val, temp2->val, cur->val);
                cur->next = temp2;
                cur = temp2;
                temp2 = temp2->next;
            }
        } else if((temp1 == NULL)) {
            cur->next = temp2;
            cur = temp2;
            temp2 = NULL;
        } else if((temp2 == NULL)) {
            cur->next = temp1;
            cur = temp1;
            temp1 = NULL;
        }
    }
                printf("=== %d\n", result->val );

    return result->next;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务