Reverse a singly linked list.
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 }