反转链表
来源:https://leetcode-cn.com/problems/reverse-linked-list/
递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(!(head&&head->next)){return head;}
struct ListNode* p=head->next;
struct ListNode* newhead=reverseList(p);
p->next=head;
head->next=NULL;
return newhead;
}
迭代
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* newhead=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* next;
newhead->next=NULL;
while(head){
next=head->next ;
head->next=newhead->next;
newhead->next=head;
head=next;
}
return newhead->next;
}