问题描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
执行结果:
迭代实现:
递归实现:
代码描述:
/**
* 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* temp = NULL; // 用于缓存cur的next数组,防止断链
ListNode* prev = head;
ListNode* cur = head->next;
head->next = NULL;
while(cur)
{
temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
head = prev;
return head;
}
};
/**
* 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 || head->next == NULL) //链表中有0个结点或者1个结点
return head;
else
{
//先反转后面的链表,从最后面的两个结点开始反转,依次向前
ListNode* newHead = reverseList(head->next);
head->next->next = head; //将后一个链表结点指向前一个结点
head->next = NULL; //将原链表中前一个结点指向后一个结点的指向关系断开
return newHead;
}
}
};
参考链接:https://blog.csdn.net/geekmanong/article/details/51097196