合并两个排序的链表的解题思路

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337?tpId=295&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page%26topicNameBigMember%3D%25E9%259D%25A2%25E8%25AF%2595TOP101%26topicIdBigMember%3D295%26pageSourceBigMember%3Dnc03%26dayCountBigMember%3D%25E8%25BF%259E%25E7%25BB%25AD%25E5%258C%2585%25E6%259C%2588

思路如下:

  1. 定义3个指针变量,用于指向链表一和链表二,一个用于指向定义的头节点;
  2. 定义一个头节点,用于指向比较完成后的第一个节点;
  3. 将链表一和链表二的指针进行比较,头节点的指针指向小的那一个节点,链表指针后移,头节点指针后移
  4. 将剩下的链表直接连接
  5. 返回头节点的下一个节点,目的去掉头节点

struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {

if(pHead1==NULL){

return pHead2;

}

if(pHead2==NULL){

return pHead1;

}

struct ListNode dummy;

struct ListNode *tail = &dummy;

while(pHead1!=NULL&&pHead2!=NULL){

if(pHead1->val<pHead2->val){

tail->next = pHead1;

pHead1 = pHead1->next;

}

else{

tail->next = pHead2;

pHead2 = pHead2->next;

}

tail = tail->next;

}

if(pHead1!=NULL){

tail->next = pHead1;

}

if(pHead2!=NULL){

tail->next = pHead2;

}

return tail->next;

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务