题目描述
实现链表反转的方法不止一种,我采用的方法算是头插之类的方法吧;
1、定义两个结点,pre、cur;
2、pre指向链表头的结点,cur指向头结点的下一个结点;
3、由cur遍历整个链表,并不断将结点插入pre与phead之间,这样就实现来反转;
为了保证算法的bugfree,记得考虑边界条件;
具体实现看代码:
/*
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;
}
else if (pHead->next == NULL)
{
return pHead;
}
ListNode *pre = new ListNode(0);
pre->next = pHead;
ListNode *cur = pHead->next;
while (cur != NULL)
{
pHead->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = pHead->next;
}
return pre->next;
}
};