Reverse Linked List
- 迭代法:
/**
1. Definition for singly-linked list.
2. struct ListNode {
3. int val;
4. struct ListNode *next;
5. };
*/
#define null 0
struct ListNode* reverseList(struct ListNode* head) {
int i;
struct ListNode *p,*q,*r;
if(head==null)
return null;
r=head->next;
p=head;
q=null;
while(r!=null){
p->next=q;
q=p;
p=r;
r=r->next;
}
p->next=q;
return p;
}
- 递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#define null 0
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode *p;
struct ListNode *q;
if(!head || !(head->next))
return head;
p=reverseList(head->next);
head->next->next=head;
head->next=null;
return p;
}