2010年7月19日 星期一

【程概】99 普考-程式實做(一)

用C語言撰寫一個函式,能將一只含有數字的單向鏈結串列(singly linked list)切割成兩個單向鏈結串列,其一只包含奇數元素,另一只包含偶數元素,請勿複製節點,切割前後都是以數字由小到大排序,假設此函式的原型 (prototype)如下:void split (node *h, node **h1, node **h2),h是切割前鏈結串列兩個單向鏈結串列指標,h1,h2是切割後兩個單向鏈結串列的指標。(25分)
其中節點的資料結構為
typedef struct node {
int d; struct node* next;
} node;

答:
#include

typedef struct node{
int d;
struct node *next;
}node;

void split(node *h, node **h1, node **h2) {
node *odd=NULL, *even=NULL;
while (h != NULL) {
if (h->d % 2 == 1){
if (odd == NULL) {
odd = h;
*h1 = h;
} else {
(*h1)->next = h;
*h1 = h;
}
} else {
if (even == NULL) {
even = h;
*h2 = h;
} else {
(*h2)->next = h;
*h2 = h;
}
}
h = h->next;
}
(*h1)->next = NULL;
(*h2)->next = NULL;
*h1 = odd;
*h2 = even;
}


int main(int argc, char *argv[])
{
int i=0; int data[] ={3,4,5,7,8};
node *p, *r;
node *h=NULL, *h1=NULL, *h2=NULL;
for (i=0; i<5; p =" (node*)malloc(sizeof(node));">d = data;
p->next = NULL;

if (h==NULL) {
h = p;
r = p;
}
else {
r->next = p;
r = p;
}
}
r = h;
while (r!=NULL) {
printf("%d, ", r->d);
r = r->next;
}
split(h, &h1, &h2);
while(h1 != NULL) {
printf("\nh1 odd data is %d", h1->d);
h1 = h1->next;
}
while(h2 != NULL) {
printf("\nh2 even data is %d", h2->d);
h2 = h2->next;
}
}

沒有留言:

張貼留言