题解 | #反转链表#
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
#定义三个指针,pre,cur和next,分别表示前向节点、当前节点和后继节点,通过改变cur指针的后续节点为pre,并不断前移三个指针,最终实现链表反转。
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL||pHead->next==NULL){
return pHead;
}else{
ListNode* pre = NULL;
ListNode* cur = pHead;
ListNode* next= NULL;
while(cur!=NULL){
next = cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
}
};
小鹏汽车工作强度 25人发布