给出一个单向链表的header,要求经过处理变成反向,即原链表尾变为链表头,原链表头变成链表尾。
例如: 10->20->30->NULL
处理后变为: 30->20->10->NULL
我想,下面这应该是时间和空间方面都最简单的方法。
struct list{
int value;
struct list* next;
};
static int reverse(struct list **pl)
{
struct list* header,*tmp;
if(*pl==NULL) return 0;
header = NULL;
//add node to header and point to next node.
while(*pl!=NULL) {tmp=*pl; *pl=(*pl)->next; tmp->next=header; header=tmp;}
*pl = header;
return 1;
}
测试:
static void print_list(struct list *pl)
{
struct list *header = pl;
printf("list:");
while(header!=NULL){
printf(" %d",header->value);
header = header->next;
}
printf("/n");
}
int _tmain(int argc, _TCHAR* argv[])
{
#define NUMBER 9
int i = 0;
int score[NUMBER] = {10,20,30,40,50,60,70,80,90};
struct list *header,*cur,*tmp;
header = cur = NULL;
//create list.
while(i < NUMBER) {
tmp = (struct list *)malloc(sizeof(struct list));
tmp->value = score[i];
tmp->next = NULL;
if(i==0)
header = cur = tmp;
else{
cur->next = tmp;
cur = cur->next;
}
i++;
}
print_list(header);
reverse(&header);
print_list(header);
reverse(&header);
print_list(header);
printf("hello,world!/n");
getch();
return 0;
}