【问题】
单链表逆序
【代码】
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct ListNode {
int value;
struct ListNode *next;
}ListNode;
typedef struct ListNode *List;
List reverseList(List head) //列表逆序
{
ListNode *rear, *curr, *front;
rear = curr = head;
while (curr != NULL) {
front = curr->next;
curr->next = rear;
rear = curr;
curr = front;
}
head->next = NULL;
head = rear;
return head;
}
List createdList(int a[], int len) //创建列表
{
int i = 1;
ListNode *head, *curr, *rear;
curr = (ListNode *)malloc (sizeof (ListNode));
curr->value = a[0];
curr->next = NULL;
head = rear = curr;
while ( i < len) {
curr = (ListNode *)malloc (sizeof (ListNode));
curr->value = a[i++];
curr->next = NULL;
rear->next = curr;
rear = curr;
}
return head;
}
void printList(List head) //打印列表
{
ListNode *curr;
curr = head;
while(curr != NULL) {
printf("%d ", curr->value);
curr = curr->next;
}
}
int main(void)
{
int a[5] = {1, 2, 3, 4, 5};
List head;
head = createdList(a, 5);
head = reverseList(head);
printList(head);
printf("\n");
return 0;
}