生活随笔
收集整理的這篇文章主要介紹了
奇数值结点链表(C语言实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
習題11-7 奇數值結點鏈表(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;
}
struct ListNode
*readlist()
{int n
;struct ListNode
*head
=NULL,*p
=NULL,*q
=NULL;scanf("%d",&n
);while(n
!=-1){if(head
== NULL){head
=(struct ListNode
*)malloc(sizeof(struct ListNode
));head
->data
=n
;p
=head
;}else{q
=(struct ListNode
*)malloc(sizeof(struct ListNode
));q
->data
=n
;p
->next
=q
;p
=q
;}scanf("%d",&n
);}p
->next
=NULL;return head
;
}struct ListNode
*getodd( struct ListNode
**L
)
{struct ListNode
*p
=NULL,*head
=NULL,*pt
=NULL,*q
=NULL,*t
=NULL,*pre
=NULL;while((*L
) && (*L
)->data
%2 == 1){q
=(struct ListNode
*)malloc(sizeof(struct ListNode
));q
->next
=NULL;q
->data
=(*L
)->data
;if(head
==NULL){head
=q
;pt
=head
;}else{pt
->next
=q
;pt
=pt
->next
;}t
=(*L
);(*L
)=(*L
)->next
;free(t
);}if(*L
== NULL)return head
;pre
=(*L
);p
=(*L
)->next
;while(p
){if(p
->data
%2 == 1){q
=(struct ListNode
*)malloc(sizeof(struct ListNode
));q
->next
=NULL;q
->data
=p
->data
;if(head
==NULL){head
=q
;pt
=head
;}else{pt
->next
=q
;pt
=pt
->next
;}t
=pre
->next
;pre
->next
=t
->next
;p
=t
->next
;free(t
);continue;}p
=p
->next
;pre
=pre
->next
;}return head
;
}
總結
以上是生活随笔為你收集整理的奇数值结点链表(C语言实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。