单链表逆序
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上次指到的指针
#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上次指到的指针
相关文章推荐
- 面试题:用 Java 逆序打印链表
- 用链表形式存储一个字符串,插入、删除某个字符,最后按正序、逆序两种方式输出字符串
- 【数据结构_链表_List_0957】逆序输出链表
- 链表逆序
- 链表逆序[c]
- 逆序建立链表
- 数据结构实验之链表二:逆序建立链表
- 【数据结构】递归实现链表逆序
- 数据结构实验之链表二:逆序建立链表
- 链表的逆序
- 链表的各种操作实现 链表逆序 链表排序 有序链表归并 链表存在环的判定
- 实现链表的逆序输出和删除某节点
- 链表逆序 和 寻找链表中间节点
- 逆序建立链表
- 无头单链表逆序(法一)
- 数据结构实验之链表二:逆序建立链表
- 链表逆序的原理及实例
- 单向链表新增逆序
- 双链表的逆序——C程序设计
- [SDUT](2117)数据结构实验之链表二:逆序建立链表 ---链式存储(线性表)