Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:A linked list can be reversed either iteratively or recursively. Could you implement both?
方法一
算法思想: 将第一个结点放在第二个结点之后,前两个结点放在第三个结点之后…依次进行。
性能:8ms faster than 100%
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *p,*q,*r;
p = head;
q = NULL;
if(!head) return head;
while(p->next)
{
r = p -> next;
p -> next = q;
q = p;
p = r;
}
p -> next = q;
return p;
}
};
方法二
算法思想:从头开始,将每一个结点插入到原链表的末尾结点之后。
性能:8ms faster than 100%
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *p,*q,*r;
p = head;
q = head;
if(!head) return head;
while(q->next) q = q -> next;
r = p -> next;
while(r != q -> next)
{
p -> next = q -> next;
q -> next = p;
p = r;
r = r -> next;
}
return q;
}
};