奇数值结点链表
習題11-7?奇數值結點鏈表???(20分)
本題要求實現兩個函數,分別將讀入的數據存儲為單鏈表、將鏈表中奇數值的結點重新組成一個新的鏈表。鏈表結點定義如下:
struct ListNode {int data;ListNode *next; };函數接口定義:
struct ListNode *readlist(); struct ListNode *getodd( struct ListNode **L );函數readlist從標準輸入讀入一系列正整數,按照讀入順序建立單鏈表。當讀到-1?1時表示輸入結束,函數應返回指向單鏈表頭結點的指針。
函數getodd將單鏈表L中奇數值的結點分離出來,重新組成一個新的鏈表。返回指向新鏈表頭結點的指針,同時將L中存儲的地址改為刪除了奇數值結點后的鏈表的頭結點地址(所以要傳入L的指針)。
裁判測試程序樣例:
#include <stdio.h> #include <stdlib.h>struct ListNode {int data;struct ListNode *next; };struct ListNode *readlist(); struct ListNode *getodd( struct ListNode **L ); void printlist( struct ListNode *L ) {struct ListNode *p = L;while (p) {printf("%d ", p->data);p = p->next;}printf("\n"); }int main() {struct ListNode *L, *Odd;L = readlist();Odd = getodd(&L);printlist(Odd);printlist(L);return 0; }/* 你的代碼將被嵌在這里 */輸入樣例:
1 2 2 3 4 5 6 7 -1輸出樣例:
1 3 5 7 2 2 4 6#include <stdio.h> #include <stdlib.h>#define N 20struct ListNode {int data;struct ListNode *next; };struct ListNode *readlist(); struct ListNode *getodd( struct ListNode **L ); void printlist( struct ListNode *L ) {struct ListNode *p = L;while (p) {printf("%d ", p->data);p = p->next;}printf("\n"); }int main() {struct ListNode *L, *Odd;L = readlist();Odd = getodd(&L);printlist(Odd);printlist(L);return 0; }struct ListNode *readlist(){int i=0,in,n,a[N];struct ListNode *h,*p,*q;scanf("%d", &in);while(in != -1){a[i]=in;i++;scanf("%d", &in);}n=i; /*for(i=0;i<n;i++)printf("%d ", a[i]);printf("\n"); */h = (struct ListNode*)malloc(sizeof(struct ListNode));h->data = a[0];h->next = NULL;p=q=h;i=1;while(i<n){q = (struct ListNode*)malloc(sizeof(struct ListNode));q->data = a[i];q->next = NULL;p->next = q;p=q;i++;}p->next=NULL;return h; }struct ListNode *getodd( struct ListNode **L ){struct ListNode *oddhead,*p,*q,*head;int a[N],i=0,n;head = *L;/*先確定head->data 不是奇數*/while(head->data%2==1){a[i++]=head->data;p = head->next;free(head);head = p;}q=head;p=head->next;while(p){if(p->data%2==1){a[i++]=p->data;q->next=p->next;free(p);p=q->next;continue;}q=p;p=p->next;}*L=head;n=i;/*調試用for(i=0;i<n;i++)printf("%d ", a[i]);printf("\n");*//*重新建立奇數值的鏈表*/oddhead = (struct ListNode*)malloc(sizeof(struct ListNode));oddhead->data = a[0];oddhead->next = NULL;p=q=oddhead;i=1;while(i<n){q = (struct ListNode*)malloc(sizeof(struct ListNode));q->data = a[i];q->next = NULL;p->next = q;p=q;i++;}p->next=NULL;return oddhead; }
總結
- 上一篇: 重温DFS
- 下一篇: (笔记本)电脑WLAN 点不开,显示WL