已知链表头结点指针head
,将链表逆序。(不可申请额外空间)
如图:
解题思路:
-
依次遍历链表结点,每遍历一个结点即逆置一个结点
-
遍历第一个结点:
-
遍历第二个结点:
5.遍历第四个结点:
-
遍历第五个结点:
具体操作过程:
-
备份
head->next
-
修改
head->next
-
修改
head
与new_head
具体代码:
ListNode* reverseList(ListNode* head)
{
ListNode* new_head = NULL;
while( head )
{
ListNode* head_next = head->next; // 备份head->next
head->next = new_head; // 更新head->next
new_head = head; // 移动new->head
head = head_next;
}
return new_head;
}
网友评论