题目:
Reverse a singly linked list.
解答:
/**
* 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) {
//空链表
//单节点链表
//双节点链表 1 -> 2 -> NULL 2 -> 1 -> NULL
//三节点链表 1 -> 2 -> 3 -> NULL 3 -> 2 -> 1 -> NULL
ListNode* frt = NULL;
ListNode* sec = head;
while(sec) {
ListNode* tmp = sec->next;
sec->next = frt;
if(!tmp) return sec;
frt = sec;
sec = tmp;
}
return sec;
}
};