#include <stdio.h>
struct node
{
node *next;
int data;
};
node *LInsert(node *head, int data);
node *LReverse(node *head);
void Lprint(node *head);
int main()
{
node *head = NULL;
for(int i=0;i<10;i++) //插入1-10到链表中
{
head = LInsert(head, i+1);
}
printf("Before Reverse:
");
Lprint(head);
head = LReverse(head);
printf("After Reverse:
");
Lprint(head);
return 0;
}
node *LInsert(node *head, int data)
{
node *p = NULL;
node *q = NULL;
if(head == NULL)
{
head = new node;
head->data = data;
head->next = NULL;
}
else
{
q = head;
p = q->next;
while(p != NULL)
{
q = p;
p = p->next;
}
p = new node;
p->data = data;
p->next = NULL;
q->next = p;
}
return head;
}
node *LReverse(node *head)
{
node *pPre = NULL;
node *pNow = NULL;
node *pNext = NULL;
if((head == NULL) || (head->next == NULL)) //no element or 1 element
{
return head;
}
else //2 or more elements
{
pPre = head;
pNow = pPre->next;
pNext = pNow->next;
while(pNext != NULL)
{
pNow->next = pPre;
pPre = pNow;
pNow = pNext;
pNext = pNext->next;
}
pNow->next = pPre; //important!!!
head->next = NULL;
return pNow;
}
}
void Lprint(node *head)
{
node *p = head;
while(p != NULL)
{
printf("%d
", p->data);
p = p->next;
}
}