题目:
Reverse a singly linked list.
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) {
//note:头为空
if( head == NULL )
return head;
ListNode* tail = head;
ListNode* temp;
while( tail->next != NULL )
{
temp = head;
head = tail->next;
tail->next = head->next;
head->next = temp;
}
return head;
}
};
总结:
1、notes:(1)注意链表为空的情况