Leetcode题目
//第一种方式,循环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
ListNode *pNode = head;//保存当前结点
ListNode *pre = NULL;//保存前驱结点
while(pNode != NULL)
{
ListNode *pNext = pNode->next;//保存后继结点
if(pNext == NULL)
{
pNode->next = pre;
return pNode;
}
pNode->next = pre;
pre = pNode;
pNode = pNext;
}
}
};
//第二种方式,递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL)
return NULL;
if(head->next == NULL)
return head;
ListNode *pNode = reverseList(head->next);//先反转后面的结点,head->next是倒数第二个结点
head->next->next = head;//下一个结点是head
head->next = NULL;//head下一个结点为NULL
return pNode;//头结点
}
};