c++解题思路,如何反转一个链表
将head放到最后一位 -->head->next作为head–>重复操作
看图解:

首先这是一个链表
定义几个指针
ListNode *preP= NULL, *curP = head, *nextP=head->next;
然后执行代码:
curP->next = preP; //将head放到最后
preP = curP;
curP = nextP;
nextP = nextP->next;
执行一次代码后得到:

leetcode完整代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL)
return NULL;
ListNode *headP=head , *nextP=head->next,*preP=NULL;
while( nextP != NULL){
headP->next=preP;
preP=headP;
headP=nextP;
nextP=nextP->next;
}
headP->next=preP;
return headP;
}
};
本文详细介绍了一种使用C++实现链表反转的有效方法。通过迭代地改变当前节点的next指针,使其指向其前一个节点,从而实现链表的反转。文章提供了详细的步骤解析和完整的LeetCode代码示例。
903

被折叠的 条评论
为什么被折叠?



