生活随笔
收集整理的這篇文章主要介紹了
单链表反转 c实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
設鏈表節點為
[cpp]?view plaincopy
typedef?struct?tagListNode{?? ????int?data;?? ????struct?tagListNode*?next;?? }ListNode,?*List;??
要求將一帶鏈表頭List head的單向鏈表逆序。
分析:
? 1). 若鏈表為空或只有一個元素,則直接返回;
??2). 設置兩個前后相鄰的指針p,q. 將p所指向的節點作為q指向節點的后繼;
? 3). 重復2),直到q為空
? 4). 調整鏈表頭和鏈表尾
示例:以逆序A->B->C->D為例,圖示如下
?
實現及測試代碼如下:
[cpp]?view plaincopy
#include?<stdio.h>?? #include?<stdlib.h>?? ?? typedef?struct?tagListNode{?? ????int?data;?? ????struct?tagListNode*?next;?? }ListNode,?*List;?? ?? void?PrintList(List?head);?? List?ReverseList(List?head);?? ?? int?main()?? {?? ?????? ????ListNode?*head;?? ????head?=?(ListNode*)malloc(sizeof(ListNode));?? ????head->next?=?NULL;?? ????head->data?=?-1;?? ?? ?????? ????int?i;?? ????ListNode?*p,?*q;?? ????p?=?head;?? ????for(int?i?=?1;?i?<=?10;?i++)?? ????{?? ????????q?=?(ListNode?*)malloc(sizeof(ListNode));?? ????????q->data?=?i;?? ????????q->next?=?NULL;?? ????????p->next?=?q;?? ????????p?=?q;?????????? ????}?? ?? ????PrintList(head);????????????? ????head?=?ReverseList(head);???? ????PrintList(head);????????????? ????return?0;?? }?? ?? List?ReverseList(List?head)?? {?? ????if(head->next?==?NULL?||?head->next->next?==?NULL)???? ????{?? ???????return?head;????? ????}?? ?? ????ListNode?*t?=?NULL,?? ?????????????*p?=?head->next,?? ?????????????*q?=?head->next->next;?? ????while(q?!=?NULL)?? ????{?????????? ??????t?=?q->next;?? ??????q->next?=?p;?? ??????p?=?q;?? ??????q?=?t;?? ????}?? ?? ?????? ????head->next->next?=?NULL;???? ????head->next?=?p;????????????? ????return?head;?? }?? ?? void?PrintList(List?head)?? {?? ????ListNode*?p?=?head->next;?? ????while(p?!=?NULL)?? ????{?? ????????printf("%d?",?p->data);?? ????????p?=?p->next;?? ????}?? ????printf("/n");?? }??
?from:http://blog.csdn.net/niuer09/article/details/5961004
總結
以上是生活随笔為你收集整理的单链表反转 c实现的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。