Reverse a singly linked list

 

每次取链表的头结点,插入当作当前链表的头

以前我写链表老是想用

while(head->next)

{

    ....

}

最后还得再考虑最后一个结点。根本没有必要:

    ListNode* reverseList(ListNode* head) {
        ListNode * p=NULL;
      
        while(head)
        {
            ListNode * temp=new ListNode (head->val);
            temp->next=p;
            p=temp;
           // if(head->next)
            head=head->next;
        }
      
        return p;
    }

 

相关文章:

  • 2021-09-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-07
猜你喜欢
  • 2021-06-13
  • 2021-12-06
  • 2021-08-30
  • 2021-08-20
  • 2021-10-13
  • 2021-12-16
  • 2021-06-24
  • 2021-12-15
相关资源
相似解决方案