标签:code def bsp || ret The nod efi amp
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Iterative:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode pre = null, nxt = null; while(head != null) { nxt = head.next; head.next = pre; pre = head; head = nxt; } return pre; } }
Recursive:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode nxt = head.next; ListNode newHead = reverseList(nxt); nxt.next = head; head.next = null; return newHead; } }
标签:code def bsp || ret The nod efi amp
原文地址:https://www.cnblogs.com/xuanlu/p/12114566.html