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?
代码:
/**
* 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 *key = NULL;
ListNode *temp;
while(head != NULL){
temp = (ListNode*)malloc(sizeof(ListNode));
temp->next = key;
temp->val = head->val;
key = temp;
head = head->next;
}
return key;*/
//第二种时间快,未占用内存,当然指针用了一点点。 指针方向翻转的思想
if(head == NULL ||head->next ==NULL)
return head;
ListNode *t,*p,*q;
t = head;
p = head->next;
t->next = NULL;
q = p;
while(q&&p){
q = p->next;
if(q){
p->next = t;
t = p;
p = q;
}
}
p->next = t;
return p;
}
};