#include "stdio.h"
#include "stdlib.h"
struct list
{
int num;
struct list *next;
};
typedef struct list node;
typedef node *link;
link createlist(int *array,int len)
{
link head;
link ptr,ptr1;
int i;
head = (link)malloc(sizeof(node));
if(!head)
return NULL;
head->num = array[0];
head->next = NULL;
ptr = head;
for(i=1;i<len;i++)
{
ptr1 = (link)malloc(sizeof(node));
if(!ptr1)
return NULL;
ptr1->num = array[i];
ptr1->next = NULL;
ptr->next = ptr1;
ptr = ptr->next;
}
return head;
}
void printlist(link head)
{
while(head)
{
printf("[%d]",head->num);
head = head->next;
}
printf("\n");
}
link invertlist(link head)
{
link pre,mid,last;
if(!head)
return NULL;
pre = head;
mid = head->next;
while(mid)
{
last = mid->next;
mid->next = pre;
pre = mid;
mid = last;
}
head->next = NULL;
head = pre;
return pre;
}
void freelist(link head)
{
link ptr;
while(head)
{
ptr = head;
head = head->next;//head = ptr->next;
free(ptr);
}
}
void main()
{
link head;
int array[6] = {1,2,3,4,5,6};
head = createlist(array,6);
printf("原链表:");
printlist(head);
printf("反转后的链表:");
head = invertlist(head);
printlist(head);
freelist(head);
}
#include "stdlib.h"
struct list
{
int num;
struct list *next;
};
typedef struct list node;
typedef node *link;
link createlist(int *array,int len)
{
link head;
link ptr,ptr1;
int i;
head = (link)malloc(sizeof(node));
if(!head)
return NULL;
head->num = array[0];
head->next = NULL;
ptr = head;
for(i=1;i<len;i++)
{
ptr1 = (link)malloc(sizeof(node));
if(!ptr1)
return NULL;
ptr1->num = array[i];
ptr1->next = NULL;
ptr->next = ptr1;
ptr = ptr->next;
}
return head;
}
void printlist(link head)
{
while(head)
{
printf("[%d]",head->num);
head = head->next;
}
printf("\n");
}
link invertlist(link head)
{
link pre,mid,last;
if(!head)
return NULL;
pre = head;
mid = head->next;
while(mid)
{
last = mid->next;
mid->next = pre;
pre = mid;
mid = last;
}
head->next = NULL;
head = pre;
return pre;
}
void freelist(link head)
{
link ptr;
while(head)
{
ptr = head;
head = head->next;//head = ptr->next;
free(ptr);
}
}
void main()
{
link head;
int array[6] = {1,2,3,4,5,6};
head = createlist(array,6);
printf("原链表:");
printlist(head);
printf("反转后的链表:");
head = invertlist(head);
printlist(head);
freelist(head);
}