本题要求实现一个合并两个有序链表的简单函数。链表结点定义如下:
struct ListNode { int data; struct ListNode *next; };
函数接口定义:
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2);
其中list1
和list2
是用户传入的两个按data
升序链接的链表的头指针;函数mergelists
将两个链表合并成一个按data
升序链接的链表,并返回结果链表的头指针。
裁判测试程序样例:
#include <stdio.h> #include <stdlib.h> struct ListNode { int data; struct ListNode *next; }; struct ListNode *createlist(); /*裁判实现,细节不表*/ struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2); void printlist( struct ListNode *head ) { struct ListNode *p = head; while (p) { printf("%d ", p->data); p = p->next; } printf(" "); } int main() { struct ListNode *list1, *list2; list1 = createlist(); list2 = createlist(); list1 = mergelists(list1, list2); printlist(list1); return 0; } /* 你的代码将被嵌在这里 */
输入样例:
1 3 5 7 -1 2 4 6 -1
输出样例:
1 2 3 4 5 6 7
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2) { int len = 0; int a[10000]; struct ListNode *p1 = list1; struct ListNode *p2 = list2; struct ListNode *head = NULL; struct ListNode *tail = NULL; struct ListNode *q; while(p1) { a[len] = p1->data; p1 = p1->next; len++; } while(p2) { a[len] = p2->data; p2 = p2->next; len++; } int i, j, temp; for(i=1; i<len; i++) { for(j=0; j<len-i; j++) { if(a[j]>a[j+1]) { temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } } for(i = 0; i < len; i++) { q = (struct ListNode *)malloc(sizeof(struct ListNode)); q->data = a[i]; if(head == NULL) { head = q; head->next = NULL; } if(tail != NULL)//tail为开辟节点 { tail->next = q; } tail = q; tail->next = NULL; } return head; }