奇数值结点链表
習(xí)題11-7?奇數(shù)值結(jié)點(diǎn)鏈表???(20分)
本題要求實(shí)現(xiàn)兩個函數(shù),分別將讀入的數(shù)據(jù)存儲為單鏈表、將鏈表中奇數(shù)值的結(jié)點(diǎn)重新組成一個新的鏈表。鏈表結(jié)點(diǎn)定義如下:
struct ListNode {int data;ListNode *next; };函數(shù)接口定義:
struct ListNode *readlist(); struct ListNode *getodd( struct ListNode **L );函數(shù)readlist從標(biāo)準(zhǔn)輸入讀入一系列正整數(shù),按照讀入順序建立單鏈表。當(dāng)讀到-1?1時(shí)表示輸入結(jié)束,函數(shù)應(yīng)返回指向單鏈表頭結(jié)點(diǎn)的指針。
函數(shù)getodd將單鏈表L中奇數(shù)值的結(jié)點(diǎn)分離出來,重新組成一個新的鏈表。返回指向新鏈表頭結(jié)點(diǎn)的指針,同時(shí)將L中存儲的地址改為刪除了奇數(shù)值結(jié)點(diǎn)后的鏈表的頭結(jié)點(diǎn)地址(所以要傳入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 不是奇數(shù)*/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;/*調(diào)試用for(i=0;i<n;i++)printf("%d ", a[i]);printf("\n");*//*重新建立奇數(shù)值的鏈表*/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; }
總結(jié)
- 上一篇: 重温DFS
- 下一篇: (笔记本)电脑WLAN 点不开,显示WL