题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* head ) {
// write code here
//assert(head!=NULL);
if(head==NULL || head->next==NULL)return head;//判断链表是否为空
struct ListNode *pre=NULL;//设置一个pre结点,置空
struct ListNode *cur=head;//设置当前节点,为头结点
while(cur!=NULL)//进入循环,当前节点不为空时,一直循环
{
struct ListNode *cur_next=cur->next;//再设置一个节点用来保存当前节点的next
cur->next=pre;//关键步骤:翻转,将当前节点翻转,其指针指向前一个节点
pre=cur;//用cur当前节点去更新pre的值
cur=cur_next;//用cur_next更新cur的值
}
return pre;//最厚返回pre,即翻转链表后的头结点的值
}
查看16道真题和解析

