题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
// public:
/*
ListNode* ReverseList(ListNode* pHead) {
ListNode *r = nullptr;
while (pHead) {
ListNode *t = pHead->next;
pHead->next = r;
r = pHead;
pHead = t;
}
return r;
}
*/
/*
第二种操作方式
*/
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode*r =nullptr;
for(;pHead;pHead=pHead->next)
{
ListNode *t =new ListNode(pHead->val);
t->next =r;
r =t;
}
return r;
}
}; 这个参考别人的
第一种写法就是将pHead指向的一个结点指向后面的结点,一次循环
第二种,则是将t 开辟一个空间,同时进行赋值(p->val)