版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
题目要求
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
先决条件:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
解题思路
法一:
给定三个指针 n1,n2,n3,n1 指向头节点,n2 指向头-> next,n3 指向头-> next -> next ,使 next 指向 prev ,即 n2 -> next = n1,n3 始终向后移动,直到 n3 指向空,即 n1 和 n2 改变指针所指方向, n3 为指针方向改变的位置
法二:
头插法:newhead,prev,next,方法和上面的方法差不多,newhead 为新头,即新链表改变指针的长度, prev -> next = newhead 为原先的规则,在 newhead 向后移动的过程中,prev 、newhead 从头节点改变指向,直到newhead 遍历完整个链表为止
解题演示
输入:1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
过程显示:
递归:
1->2->3->5->4->NULL
1->2->5->4->3->NULL
1->5->4->3->2->NULL
5->4->3->2->1->NULL
迭代:
2->1->3->4->5->NULL
3->2->1->4->5->NULL
4->3->2->1->5->NULL
5->4->3->2->1->NULL
解题代码
上述方法有两种代码表示法:
- 递归法
struct ListNode *reverseList(struct ListNode *head)
{
if (!head)
{
return NULL;
}
if (!head->next)
{
return head;
}
struct ListNode *newhead = reverseList(head->next);
head->next->next = head; //将当前节点作为下一个节点的next节点
head->next = NULL; //将取下的节点断开原链
return newhead;
}
- 迭代法
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL)
return head;
struct ListNode *prev = NULL;
struct ListNode *newhead = head;
struct ListNode *next;
while(newhead){
next = newhead->next;
newhead->next = prev;
prev = newhead;
newhead = next;
}
// 循环结束后,newhead == NULL
// prev 即最后一个节点,也就是新的头节点
return prev;
}