题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
这道题的解题思路其实很简单的,既然是反转,那么我们就定义一个新的链表头newhead,然后遍历链表,将其中的每一个结点拿下来,然后插入到新的链表就行了,这里需要好好去巩固一下头插法和尾插法就行了
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL||pHead->next==NULL)
return pHead;
ListNode* newhead = new ListNode(-1);
ListNode* once = pHead;
int i = 0 ;
while(once!=NULL)
{
ListNode* cur = once;
cout<<"cur val = "<<once->val<<endl;
once = once->next;
cur->next = NULL;
//将当前节点插入newhead
if(i==0)
{
newhead->next = cur;
}
else{
cur->next = newhead->next;
newhead->next = cur;
}
i++;
}
return newhead->next;
}
};
