首刷自解(类似于在链表的头上插入节点) 迭代
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* H=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* ptr;
H->next=NULL;
while(head)
{
ptr=head;
head=head->next;
ptr->next=H->next;
H->next=ptr;
}
return H->next;
}
无哨兵节点解法
、/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* pre=NULL;
struct ListNode* cur=head;
while(cur)
{
struct ListNode* next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
首刷递归自解(error:返回的始终都是第一个节点 例:1<-2<-3返回的始终是1所对应的那个节点)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL||head->next==NULL)
return head;
head->next=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return head;
}
官解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL||head->next==NULL)
return head;
struct ListNode* NewHead=reverseList(head->next);//重点:关于Newhead的理解 递归一层一层入栈 开始出栈时 NewHead0指向最后一个节点然后return NewHead0,使得下层的NewHead1指向NewHead0 然后return NewHead1,使得下层的NewHead2指向NewHead1,以此类推,最终返回的NewHeadN是指向原链表的最后一个节点的,也就是反转后链表的第一个节点,上图与之对应!
head->next->next=head;
head->next=NULL;//head->next=head->next->next error:指回了自己本身 例:1->2->3->4 本条语句不能跟上条语句调换位置 否则head->next==NULL head->next->next就会发生错误
return NewHead;
}