题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ #include <stdlib.h> struct ListNode* ReverseList(struct ListNode* head ) { if(head!=NULL){ struct ListNode *pre=malloc(sizeof(struct ListNode)); struct ListNode *nxt=malloc(sizeof(struct ListNode)); struct ListNode *tmp=head; if(tmp->next!=NULL){//主体部分,原节点既有前节点也有后节点。 nxt=tmp->next;tmp->next=NULL;pre=tmp;tmp=nxt;//原head没有前节点,特殊处理为NULL while(tmp->next!=NULL){ nxt=tmp->next;tmp->next=pre;pre=tmp;tmp=nxt; } nxt->next=tmp;tmp->next=pre;//原尾节点加上空节点,充当头指针 return nxt; }else{ return head;//单节点情况,可以和空节点合并 } }else { return head;//空节点情况 } }