题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
使用三个指针实现:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr || pHead->next == nullptr) {
return pHead;
}
ListNode *cur = pHead;//at leat 2 nodes.
ListNode *head = pHead;
ListNode *next = nullptr;
while(cur->next != nullptr) {
//1st step:
next = cur->next;//
cur->next = cur->next->next;// pull cur->next;
next->next = head;
head = next;
//cout << head->val << endl;
}
return head;
}
};