第二关——手写反转链表
建立虚拟头结点辅助反转
思路如图
代码实现
struct ListNode* reverseList(struct ListNode*head)
{
struct ListNode* ans=(struct ListNode*)malloc(sizeof(struct ListNode));
ans->next=NULL;
struct ListNode* ans=head;
while(cur->!=NULL)
{
struct ListNode* next=cuu->next;//先创建一个新的变量next,指向cur
cur->next=ans->next;//先连接右边的箭头
ans->next=cur;//连接左边的箭头
cur=next;//更新cur的位置
}
return ans->next;
};
直接操作链表实现反转
思路如图
struct ListNode* reverseList(struct ListNode*head)
{
struct ListNode* curr=head;
struct ListNode* prev=NULL;
while(curr->next!=NULL)
{
struct ListNode* next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
return prev;
};