反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解决思路:
①迭代
代码:
/**
* 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;
struct ListNode *q = head;
struct ListNode *new_head = head;
while (q->next)
{
p = q->next;
q->next = q->next->next;
p->next = new_head;
new_head = p;
p = q->next;
}
return new_head;
}
②递归
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if (head == NULL || head->next == NULL)
return head;
struct ListNode *new_head = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return new_head;
}