反转链表
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL)return NULL;
if(pHead->next==NULL)return pHead;
ListNode*pre=NULL;//当前点的前面
ListNode*now=pHead;//当前点
ListNode*next=pHead->next;//当前点的后面
while(next)//如果后面还有点的话
{
now->next=pre;//由于要反转,所以当前点的前面那个元素会变成新的next
pre=now;//当前点变为之前的点
now=next;//当前点向后进
next=next->next;
}
now->next=pre;//最后一步,把当前点的(其实是链表的末尾)next设置为前一个
return now;//返回新的头
}
};
个人觉得效率不高,但是应该是很好理解的了