您的位置:首页 > 编程语言 > C语言/C++

单链表逆序

2016-11-13 20:12 148 查看
#include <cstddef>

#include <iostream>

using namespace std;

 struct ListNode {

      int val;

      ListNode *next;

    ListNode(int x) : val(x), next(NULL) {}

 };

class Solution {

public:

    ListNode* reverseList(ListNode* head) {

        ListNode *p1=head;//store the current p1
ListNode *p2=NULL;// store the next p1
ListNode *p3=NULL;// store the original p1

while(p1){
if(p1==NULL) return p1;
   p2=
p1->next;// p2 moves on
// p2->next=p1; //p2 points to p1
p1->next = p3;//p1 points to oringinal p1(which is p3)
p3=p1;// p3 store the  original  p1
p1=p2;// p1 move on

}
return p1;

    }

};

int main()

{
ListNode a1(1);
ListNode a2(2);
ListNode a3(3);
ListNode *head=&a1;
head->next=&a2;
head->next->next=&a3;
Solution s;
s.reverseList(head);
}

用三个指针来算,p1表示当前指针(p1依次遍历所有元素),p2表示下次p1要指到的指针,p3表示p1上次指到的指针
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 单链表 LeetCode