1.思路:
老方法,但一定要记住需要定义三个指针,head, pre, cur;并需要判断链表是否为空。
2.代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL) return NULL; // 判断链表是否存在
ListNode* pre = pHead; // 需要定义3个指针!!
ListNode* cur = pHead->next;
ListNode* head = pHead;
while(cur != NULL) {
head->next = cur->next;
cur->next = pre;
pre = cur;
cur = head->next;
}
return pre;
}
};