单链表逆序
http://blog.csdn.net/niuer09/article/details/5961004
- 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为例,图示如下
实现及测试代码如下:
- #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");
- }