206 Reverse Linked List
链接:https://leetcode.com/problemset/algorithms/
问题描述:
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
这个问题是链表求逆,废话不多,直接上代码吧。
递归版:
struct ListNode* reverseList(struct ListNode* head)
{
if(head==NULL||head->next==NULL) return head;
struct ListNode *temp1=head;
struct ListNode *temp2;
while(temp1->next!=NULL)
{
temp2=temp1;
temp1=temp1->next;
}
temp2->next=NULL;
temp1->next=temp2;
reverseList(head);
return temp1;
}
非递归版:
struct ListNode* reverseList(struct ListNode* head)
{
if(head==NULL||head->next==NULL) return head;
struct ListNode *temp1=NULL;
struct ListNode *temp2=NULL;
while(head!=NULL)
{
temp2=head->next;
head->next=temp1;
temp1=head;
head=temp2;
}
return temp1;
}