首先判断链表是否为空(没写会出现段错误)
定义三个指针,cur指的是当前元素,pre指的是前一个元素,nextcur需要保存的是下一个元素,也就是下一次循环时的当前元素。
/*
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;
ListNode* cur = pHead->next;
ListNode* nextcur = pHead;
while(cur != NULL){
nextcur -> next = cur -> next;
cur -> next = pre;
pre = cur;
cur = nextcur -> next;
}
return pre;
}
};