6-2 刪除單鏈表偶數節點 (20 分)
阿新 • • 發佈:2019-01-04
本題要求實現兩個函式,分別將讀入的資料儲存為單鏈表、將連結串列中偶數值的結點刪除。連結串列結點定義如下:
struct ListNode {
int data;
struct ListNode *next;
};
函式介面定義:
struct ListNode *createlist();
struct ListNode *deleteeven( struct ListNode *head );
函式createlist從標準輸入讀入一系列正整數,按照讀入順序建立單鏈表。當讀到−1時表示輸入結束,函式應返回指向單鏈表頭結點的指標。
函式deleteeven將單鏈表head中偶數值的結點刪除,返回結果連結串列的頭指標。
裁判測試程式樣例:
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *createlist();
struct ListNode *deleteeven( struct ListNode *head );
void printlist( struct ListNode *head )
{
struct ListNode *p = head;
while ( p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
struct ListNode *head;
head = createlist();
head = deleteeven(head);
printlist(head);
return 0;
}
/* 你的程式碼將被嵌在這裡 */
輸入樣例:
1 2 2 3 4 5 6 7 -1
輸出樣例:
1 3 5 7
typedef struct ListNode *List;
struct ListNode *createlist()
{ //尾插法讀入順序建立連結串列,-1為結束符
List head=NULL, tail=NULL;
int t;
scanf("%d",&t);
while(t != -1){
List temp = (List)malloc(sizeof(struct ListNode));
temp->data = t;
temp->next = NULL;
if(tail==NULL)
head = tail = temp;
else{
tail->next = temp;
tail = temp;
}
scanf("%d",&t);
}
return head;
}
struct ListNode *deleteeven( struct ListNode *head )
{
List p=head,q;
while(head && head->data%2==0){ //保證頭結點不是偶數
p = head;
head = head->next;
free(p);
}
//head空指標或者指向一個奇數節點,外層迴圈判斷到結尾,內層迴圈連續刪除
p = head;
while(p && p->next){
while(p->next && p->next->data%2==0){
q = p->next;
p->next = q->next;
}
p = p->next;
}
return head;
}
或者直接將所有奇數節點提取出來建立新的連結串列返回,而不是刪除偶數節點
struct ListNode *deleteeven( struct ListNode *head )
{
List newhead=NULL,p=head,tail;
while(p){
if(p->data%2==1){
List temp = (List)malloc(sizeof(struct ListNode));
temp->data = p->data;
temp->next = NULL;
if(newhead==NULL)
newhead = tail = temp;
else{
tail->next = temp;
tail = temp;
}
}
p = p->next;
}
return newhead;
}