链表翻转

来源:互联网 发布:中异软件切割 编辑:程序博客网 时间:2024/05/21 12:44

思路:两两交换,每交换一次指针向后移动一次,最后断开原来的头指针,再加上新的头指针。

#include<stdio.h>

#include<stdlib.h>
typedef struct Listnode{
struct Listnode *next;
int n;
}ListNode, *List;
void PrintList(ListNode *head);
//List ReverseList(List head);
void main()
{
ListNode *head,*p,*t;
head=(ListNode*)malloc(sizeof(ListNode));
head->next=NULL;
head->n=-1;
int i;
t=head;
for(i=1;i<10;i++)
{
p=(ListNode*)malloc(sizeof(ListNode));
p->n=i;
t->next=p;
p->next=NULL;
t=p;
}
printList(head);
head=ReverseList(head);
printList(head);
}
    List ReverseList(List head)
{*-+
ListNode *p,*q,*t;
p=head->next;
q=p->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(ListNode *head){
ListNode *p;
p=head->next;
while(p!=NULL)
{
printf("%d",p->n);
p=p->next;
}
}


0 0