Reverse a singly linked list.

click to show more hints.

 

Subscribe to see which companies asked this question.

 

利用循环。

 注意反转后,原来的头节->next = null

 1 class Solution {
 2 public:
 3     ListNode* reverseList(ListNode* head) {
 4         if(head == nullptr || head->next == nullptr) return head;
 5         ListNode* pre = nullptr;
 6         ListNode* cur = head;
 7         while(cur != nullptr) {
 8             ListNode* c_next = cur->next;
 9             cur->next = pre;
10             pre = cur;
11             cur = c_next;
12         }
13         return pre;
14     }
15 };

 

 递归版


 1 public class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         if(head == null ||head.next == null) return head;
 4         ListNode pre = head;
 5         head = head.next;
 6         ListNode newhead = reverseList(head);
 7         pre.next = null;
 8         head.next = pre;
 9         return newhead;
10         
11     }
12 }

 

 

 

相关文章:

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