Reverse a singly linked list.
click to show more hints.
Hint:
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
递归实现 runtime 64ms(感觉递归的效率真的好低!):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head)
{
if(head==NULL)
{
return NULL;
}
if(head->next==NULL)
{
return head;
}
struct ListNode *head1,*node,*p;
node=head->next;
head1=reverseList(node);
p=head1;
while(p->next!=NULL)//把head加在链表的末尾
{
p=p->next;
}
p->next=head;
head->next=NULL;
return head1;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head)
{
if(head==NULL)
{
return NULL;
}
if(head->next==NULL)
{
return head;
}
struct ListNode *head1,*p,*tmp;
struct ListNode *node=(struct ListNode *)malloc(sizeof(struct ListNode));
head1=head;
node->next=head1;//给链表增加一个头,用来表示链表的开始
p=head;
while(p->next!=NULL)
{
tmp=p->next;
p->next=tmp->next;//p->next=p->next->next
node->next=tmp; //将tmp放在表头之后
tmp->next=head1;
head1=tmp; //让head1指向tmp
}
free(node);
return head1;
}