题目描述
Example
For linked list 1->2->3, the reversed linked list is 3->2->1
链接地址
http://www.lintcode.com/en/problem/reverse-linked-list/
解法1
ListNode *reverse(ListNode *head) {
// write your code here
if (head == NULL) {
return head;
}
ListNode *pre = head;
ListNode *cur = pre->next;
while (cur != NULL) {
ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
head->next = NULL;
return pre;
}
很普通的解法,其中head->next置为NULL,千万别忘了
解法2
ListNode *reverse(ListNode *head) {
// write your code here
if (head == NULL) {
return head;
}
ListNode *pre = NULL;
while (head != NULL) {
ListNode *temp = head->next;
head->next = pre;
pre = head;
head = temp;
}
return pre;
}
改答案比较漂亮,少了一个变量