6-3リンクリストスプライシング(20ポイント)
この質問では、2つの順序付けられたリンクリストをマージする単純な関数を実現する必要があります。リンクリストノードは次のように定義されます。
struct ListNode {
int data;
struct ListNode *next;
};
関数インターフェイスの定義:
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2);
その中で、list1とlist2は、ユーザーから渡されたデータの昇順でリンクされている2つのリンクリストのヘッドポインターです。関数mergeistsは、2つのリンクリストを、データの昇順でリンクされているリンクリストにマージします。結果のリンクリストのヘッドポインタを返します。
審判のテスト手順の例:
#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("\n");
}
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
#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("\n");
}
int main() {
struct ListNode *list1, *list2;
list1 = createlist();
list2 = createlist();
list1 = mergelists(list1, list2);
printlist(list1);
return 0;
}
struct ListNode *newNode(int x) ;
struct ListNode *listInsrt(struct ListNode *list, int data, struct ListNode **rear) {
if (list == NULL) {
list = newNode(data);
*rear = list;
return list;
}
(*rear)->next = newNode(data);
*rear = (*rear)->next;
return list;
}
struct ListNode *createlist() {
struct ListNode *list = NULL, *rear = NULL;
int x;
while (scanf("%d", &x) && x != -1) {
list = listInsrt(list, x, &rear);
}
return list;
}
/* 你的代码将被嵌在这里 */
struct ListNode *newNode(int x) {
struct ListNode *a = (struct ListNode *) malloc(sizeof(struct ListNode));
a->data = x;
a->next = NULL;
return a;
}
struct ListNode *little(struct ListNode *newlist, int data, struct ListNode **rear) {
struct ListNode *newN = newNode(data);
if (newlist == NULL)newlist = newN;
else {
if (newlist->next == NULL) {
newlist->next = newN;
*rear = newlist->next;
newlist->next = *rear;
} else {
(*rear)->next = newN;
*rear = (*rear)->next;
}
}
return newlist;
}
struct ListNode *mergelists(struct ListNode *list1, struct ListNode *list2) {
struct ListNode *newlist = NULL, *rear = newlist;
while (list1 && list2) {
while (list1 && list2 && list1->data < list2->data) {
newlist = little(newlist, list1->data, &rear);
list1 = list1->next;
}
while (list1 && list2 && list1->data >= list2->data) {
newlist = little(newlist, list2->data, &rear);
list2 = list2->next;
}
}
while (list1) {
newlist = little(newlist, list1->data, &rear);
list1 = list1->next;
}
while (list2) {
newlist = little(newlist, list2->data, &rear);
list2 = list2->next;
}
return newlist;
}