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?
新建一个链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode * newHead , *p ;
p = head;
newHead = NULL;
while (p != NULL)
{
ListNode * newp = new ListNode(p->val);
newp->next = newHead;
newHead = newp;
p = p->next;
}
return newHead;
}
};
不新建
class Solution {
public:
ListNode* reverseList(ListNode * head) {
ListNode* prev = NULL;
ListNode* cur = head;
while (cur != NULL){
ListNode *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};