PTA 奇数值结点链表 超详细
生活随笔
收集整理的這篇文章主要介紹了
PTA 奇数值结点链表 超详细
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
PTA 奇數(shù)值結(jié)點(diǎn)鏈表
本題要求實(shí)現(xiàn)兩個(gè)函數(shù),分別將讀入的數(shù)據(jù)存儲(chǔ)為單鏈表、將鏈表中奇數(shù)值的結(jié)點(diǎn)重新組成一個(gè)新的鏈表。鏈表結(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時(shí)表示輸入結(jié)束,函數(shù)應(yīng)返回指向單鏈表頭結(jié)點(diǎn)的指針。
函數(shù)getodd將單鏈表L中奇數(shù)值的結(jié)點(diǎn)分離出來,重新組成一個(gè)新的鏈表。返回指向新鏈表頭結(jié)點(diǎn)的指針,同時(shí)將L中存儲(chǔ)的地址改為刪除了奇數(shù)值結(jié)點(diǎn)后的鏈表的頭結(jié)點(diǎn)地址(所以要傳入L的指針)。
裁判測(cè)試程序樣例:
#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這里第二個(gè)函數(shù)傳過來的是一個(gè)二級(jí)指針,指向指針的指針?biāo)栽湵眍^指針其實(shí)是*L,并不是**L這個(gè)得搞清楚。
多級(jí)指針實(shí)驗(yàn)代碼
輸出結(jié)果
AC代碼(C語言)
struct ListNode* readlist()//創(chuàng)建鏈表 {int data;struct ListNode* head = NULL;struct ListNode* prev = NULL, * current;while (scanf("%d", &data) && data != -1)//讀入-1時(shí)輸入結(jié)束{current = (struct ListNode*)malloc(sizeof(struct ListNode));if (head == NULL)head = current;elseprev->next = current;current->next = NULL;current->data = data;prev = current;}return head; } struct ListNode* getodd(struct ListNode** L) {struct ListNode* newhead = NULL, * newcurrent = NULL, * newprve = NULL;//用于創(chuàng)建新鏈表struct ListNode* newL = *L;//保存原始鏈表的表頭struct ListNode* kill = NULL;struct ListNode* prve = (*L);//初始化為原始鏈表的表頭,用于刪除節(jié)點(diǎn)while (*L)//遍歷原始鏈表{if ((*L)->data % 2 == 1){/*遇到存儲(chǔ)的數(shù)據(jù)為奇數(shù)的鏈表就提取出來創(chuàng)建一個(gè)新的鏈表存儲(chǔ),然后刪除原始鏈表中存儲(chǔ)該數(shù)據(jù)的節(jié)點(diǎn)。*/newcurrent = (struct ListNode*)malloc(sizeof(struct ListNode));if (newhead == NULL)newhead = newcurrent;elsenewprve->next = newcurrent;newcurrent->data = (*L)->data;newcurrent->next = NULL;newprve = newcurrent;if ((*L) == newL)//被刪節(jié)點(diǎn)是鏈表頭newL = newL->next;elseprve->next = (*L)->next;//刪除節(jié)點(diǎn)kill = (*L);(*L) = (*L)->next; free(kill);//釋放內(nèi)存}else{prve = (*L);(*L) = (*L)->next;} }*L = newL;//L中存儲(chǔ)的地址改為刪除了奇數(shù)值結(jié)點(diǎn)后的鏈表的頭結(jié)點(diǎn)地址return newhead; }總結(jié)
以上是生活随笔為你收集整理的PTA 奇数值结点链表 超详细的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2020第十一届蓝桥杯C/C++国赛B组
- 下一篇: (原创)六度拓扑(www.6dtop.c