單鏈表逆序
http://blog.csdn.net/niuer09/article/details/5961004測試
- typedef struct tagListNode{
- int data;
- struct tagListNode* next;
- }ListNode, *List;
要求將一帶鏈表頭List head的單向鏈表逆序。spa
分析:.net
1). 若鏈表爲空或只有一個元素,則直接返回;指針
2). 設置兩個先後相鄰的指針p,q. 將p所指向的節點做爲q指向節點的後繼;blog
3). 重複2),直到q爲空ip
4). 調整鏈表頭和鏈表尾get
示例:以逆序A->B->C->D爲例,圖示以下string
![](http://static.javashuo.com/static/loading.gif)
實現及測試代碼以下:it
- #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");
- }