题解 | #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

//关键点:1.画图,把图画出来,题就出来了,
//2.要考虑特殊情况,如输入为空时...
//注意:这个题目的链表是不带头结点的
//算法思路:设置一个头结点,p指向第一个结点,q指向p的next,q不为空,
//执行:p->next=q->next;
// q->next=head->next;
// head->next=q;
// q=p->next;

struct ListNode* ReverseList(struct ListNode* pHead)
{
struct ListNode head,p=pHead,*q=pHead->next;
if(p == NULL)
return p;
head=(struct ListNode *)malloc(sizeof(struct ListNode));
head->next=p;
while (q != NULL)
{
p->next=q->next;
q->next=head->next;
head->next=q;
q=p->next;
if(q==NULL)
break;
}
return head->next;
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务