/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *newHead;
struct ListNode *reverseNode(struct ListNode* node)
{
if(node == NULL)
return NULL;
struct ListNode *node1 = node; //指向当前结点
struct ListNode *node2 = NULL; //指向下一个结点
if(node1->next != NULL) //向后一直找到尾结点为止
{
node2 = reverseNode(node1->next); //递归关键一步:函数返回的node1,成为上一层的node2
}
else //到尾结点了
{
newHead = node1; //让新头指向原尾结点
return node1;
}
node2->next = node1; //让下一个节点的next指向当前结点 ,实现翻转效果
return node1;
}
struct ListNode* reverseList(struct ListNode* head)
{
newHead = head;
if(newHead == NULL || newHead->next == NULL)
return newHead;
//此处开始调用递归函数,最后一次返回的是原头结点,是新的尾结点
reverseNode(head)->next = NULL; //不要忘了让新的尾结点的next指向null
return newHead;
}
大概思路: