/** * struct ListNode { * int val; * struct ListNode *next; * }; * * C语言声明定义全局变量请加上static,防止重复定义 */ /** * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ // struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) { // // write code here // struct ListNode* p = pHead1; // struct ListNode* t = pHead2; // struct ListNode* save; // if(pHead1 == NULL) // return pHead2; // if(pHead2 == NULL) // return pHead1; // if(pHead1 == NULL && pHead2 == NULL) // return NULL; // /*第一种情况 // p: 1,3,5 // t: 2,4,6 // */ // /*如果t的第后一个元素,小于p的第一个元素*/ // while(t->next != NULL){ // t = t->next; // } // if(t->val < p->val){ // t->next = p; // return pHead2; // } // t = pHead2; // /*如果p的最后一个元素,小于t的第一个元素*/ // while(p->next != NULL){ // p = p->next; // } // if(p->val < t->val){ // save = t; // p->next = t; // return pHead1; // } // for(p = pHead1; p->next != NULL, t != NULL; p = p->next){ // if((p->val < t->val && p->next->val > t->val) || (p->val == t->val)){ // /*将当前t节点插入p链表中*/ // save = t; // t = t->next; // save->next = p->next; // p->next = save; // //p = p->next; // } // } // if(t != NULL){ // save = t; // p->next = save; // return pHead1; // } // /*第二种情况 // p: 2,4,6 // t: 1,3,5 // */ // // p: 123 // // t:456 // // p: 456 // // t: 123 // return pHead1; // } /* 第二种方法·穿针引线法,将两个链表中的元素,按照从小到大的顺序链接好*/ struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) { struct ListNode* p = pHead1; struct ListNode* t = pHead2; struct ListNode* save; struct ListNode* NewNode = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* NewNodePointer = NewNode; if(pHead1 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; while(p&&t){ if(p->val <= t->val){ NewNodePointer->next = p; NewNodePointer = NewNodePointer->next; p = p->next; } else{ NewNodePointer->next = t; NewNodePointer = NewNodePointer->next; t = t->next; } } /*如果有一方已经是NULL*/ if(p == NULL){ NewNodePointer->next = t; } if(t == NULL){ NewNodePointer->next = p; } //释放已经申请的头结点 save = NewNode; NewNode = NewNode->next; free(save); return NewNode; }