#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
typedef struct stu{
int id; //學號
char sex[10]; //性別
float score; //成績
struct stu *next; //下一節點的頭指針
} STU;
STU *create(){
STU *p1,*p2,*head;
int n=0;
p1 = p2 = (STU*)malloc(sizeof(STU));
scanf("%d,%f,%s",&p1->id,&p1->score,&p1->sex);
head = NULL;
while(p1->id != 0){
n++;
if(n == 1)
head = p1; //把第一個節點指針賦值給頭指針
else
p2->next = p1; //如果是第2.....n個節點 把新分配的p1地址賦值給當前節點的下一個指針元素
p2 = p1; //當前節點指針同步到新的分配內存地址
p1 = (STU*)malloc(sizeof(STU)); //分配新的內存空間
scanf("%d,%f,%s",&p1->id,&p1->score,&p1->sex);
}
p2->next = NULL; //跳出循環後當前節點的下一頭指針值爲NULL
return head;
}
/**
* 移動指針操作
*/
void MoveNode(STU** destRef, STU** sourceRef)
{
/* the front source node */
STU* newNode = *sourceRef;
assert(newNode != NULL);
/*Advance the source pointer */
*sourceRef = newNode->next;
/* Link th eold dest off the new node */
newNode->next = *destRef;
/*Move dest to point to the new node */
*destRef = newNode;
}
STU* SortedMerge(STU* a, STU* b)
{
STU* result = NULL;
/*point to the last result pointer */
STU** lastPtrRef = &result;
while(1)
{
if(a == NULL)
{
*lastPtrRef = b;
break;
}
else if(b == NULL)
{
*lastPtrRef = a;
break;
}
if(a->id <= b->id)
{
MoveNode(lastPtrRef, &a);
}
else
{
MoveNode(lastPtrRef, &b);
}
/*tricky:advance to point to the next ".next" field */
lastPtrRef = &((*lastPtrRef)->next);
}
return (result);
}
int main() {
STU *p,*psed,*new,*po,*pl;
p = create(); //新建一個鏈表
psed = create(); //新建第二個鏈表
po = p;
pl = psed;
printf("第一個鏈表:\n");
while(1){
printf("%d\t%s\t%0.2f\n",p->id,p->sex,p->score);
p=p->next;
if(p == NULL)
break;
}
printf("第二個鏈表:\n");
while(1){
printf("%d\t%s\t%0.2f\n",psed->id,psed->sex,psed->score);
psed=psed->next;
if(psed == NULL)
break;
}
printf("\n");
new = SortedMerge(po,pl);
printf("合併的鏈表:\n");
while(1){
printf("%d\t%s\t%0.2f\n",new->id,new->sex,new->score);
new=new->next;
if(new == NULL)
break;
}
return EXIT_SUCCESS;
}
【C語言】合併,排序兩個鏈表
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.