/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
//c语言声明定义全局变量需加上static,防止重复定义
//分三种情况
//第一种:头结点指针pHead为null
//第二种:只有一个结点,即pHead->next为null
//第三种:有两个以上的结点
//首先将pHead->next存放到p中
//然后将pHead->next为null,此时pHead就是新反转链表的头指针了
//接着写出一个while循环,条件是p->next不为null
//暂存p->next于temp中
//修改p->next为pHead,即接上反转链表
//更新pHead为p,再次成为反转链表的头指针
//更新p为temp,方便参与循环
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead )
{
// write code here
//第一种情况:头结点指针为pHead为NULL
if(pHead == NULL)
{
return NULL;
}
//第二种情况只有一个结点pHead->next == NULL
if (pHead->next == NULL)
{
return pHead;
}
//第三种情况:有两个以上的结点
struct ListNode *p = NULL;
struct ListNode *temp = NULL;
p = pHead->next; //首先将pHead->next存放到p中
pHead->next = NULL; //然后将pHead->next为null,此时pHead就是新反转链表的头指针了
//一个while循环,条件是p->next不为null
while(p->next != NULL)
{
temp = p->next; //暂存p->next于temp中
p->next = pHead; //修改p->next为pHead,即接上反转链表
pHead = p; //更新pHead为p,再次成为反转链表的头指针
p = temp; //更新p为temp,方便参与循环
}
//循环结束时,旧链表还剩p指向的结点没连入新反转链表中
p->next = pHead;
pHead = p;
return pHead;
}