链表反转,我首先想到的就是头插法。在这里提供两种头插法思路。一种是操作指针,一种是操作数值。
指针操作
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* p) {
ListNode *r = 0;
while (p) {
ListNode *t = p->next;
p->next = r;
r = p;
p = t;
}
return r;
}
};值操作
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* p) {
ListNode *r = 0;
for (; p; p = p->next) {
ListNode *t = new ListNode(p->val);
t->next = r;
r = t;
}
return r;
}
};
京公网安备 11010502036488号