0
点赞
收藏
分享

微信扫一扫

反转链表(C语言)

码农K 2022-01-06 阅读 88

文章目录

题目来源(力扣):反转链表

解法一

struct ListNode* reverseList(struct ListNode* head){
   struct ListNode* prev = NULL;
   struct ListNode* cur = head;
   while (cur)
   {
       struct ListNode* next = cur->next; //保存好cur下一次要指向的节点
       cur->next = prev;
       prev = cur;
       cur = next;
   }

   return prev;
}

解法二

struct ListNode* reverseList(struct ListNode* head){
   struct ListNode* cur = head;
   struct ListNode* newhead = NULL;
   while (cur)
   { 
       struct ListNode* next = cur->next;  //头插前先用next保存cur下次要指向的节点
       //头插
       cur->next = newhead;
       newhead = cur;
       cur = next;
   }
   return newhead;
}

本专栏
有关链表的题目

其它专栏
有关数组的题目

举报

相关推荐

0 条评论