头插法反转 alt

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */

/**
 * 
 * @param pHead ListNode类 
 * @return ListNode类
 */
struct ListNode* ReverseList(struct ListNode* pHead ) {
    // write code here
    struct ListNode* new_tail=pHead; //反转链表,则曾经的头节点变为尾节点,初始化新链表最后一个节点
    struct ListNode* node=pHead->next; //初始化链表节点用来遍历头插
    
    if(!pHead){
        return pHead;
    }
    new_tail->next=NULL; //新尾巴的next为空
    struct ListNode* new_head; //初始化new_head用来接收新插入的头节点
    struct ListNode* pre=new_tail; //初始化pre记录头节点插入后next应该指向谁
    while(node){ //当node不是空时
        new_head=node; //新头节点,是原链表中next出来的 
        node=node->next; //新头节点接收完毕,node取node的next
        new_head->next=pre; //新头next指向旧头
        pre=new_head; //pre指向新头
    }
    
    return new_head;
    
}