奇数值结点链表 (20 分)
生活随笔
收集整理的這篇文章主要介紹了
奇数值结点链表 (20 分)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本題要求實現兩個函數,分別將讀入的數據存儲為單鏈表、將鏈表中奇數值的結點重新組成一個新的鏈表。鏈表結點定義如下:
struct ListNode {int data;ListNode *next;};函數接口定義:
struct ListNode *readlist(); struct ListNode *getodd( struct ListNode **L );函數readlist從標準輸入讀入一系列正整數,按照讀入順序建立單鏈表。當讀到?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 6code
struct ListNode *readlist() {typedef struct ListNode *list;list head,p,t;//head為頭結點,p為結點,t為臨時結點head=(list)malloc(sizeof(struct ListNode));head->next=NULL; //頭結點指針域為空,空鏈表,且頭結點數據域未存儲信息,數據從下一個結點開始存儲t=head;while(1){p=(list)malloc(sizeof(struct ListNode));scanf("%d",&p->data);if(p->data==-1){break;}p->next=NULL;t->next=p;t=p;}return head; }/*函數getodd將單鏈表L中奇數值的結點分離出來,重新組成一個新的鏈表。 返回指向新鏈表頭結點的指針,同時將L中存儲的地址改為刪除了奇數值結點后的鏈表的頭結點地址*/ struct ListNode *getodd( struct ListNode **L ) {typedef struct ListNode *list;list p,t2; //P為新鏈表的結點,t2為臨時結點list head,t1,q; //head為新鏈表的頭指針,q為新鏈表的結點,t1為臨時結點p=(*L)->next; //P指向頭結點的下一個t2=*L; //t2初始化為p的上一個結點,下面的delete結點的操作會使用到/*奇數值結點的新鏈表頭指針新建*/head=(list)malloc(sizeof(struct ListNode));head->next=NULL;t1=head;//遍歷單鏈表while(p){if(p->data%2){/*創建奇數值結點的新鏈表*/q=(list)malloc(sizeof(struct ListNode));q->data=p->data;t1->next=q;q->next=NULL;t1=q;/*從舊的鏈表中刪除奇數值結點*/t2->next=p->next;free(p);p=t2;}t2=p; //t2始終為p的上一個結點p=p->next;}*L=(*L)->next; //頭結點未存儲數據,指向下一個結點,配合輸出函數進行輸出return head->next; }總結
以上是生活随笔為你收集整理的奇数值结点链表 (20 分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode每日一题2020.11.
- 下一篇: 物理层(网线)、数据链路层(交换机)、网