标签:tno span efi inpu style color 一个 node lis
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?
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { ListNode cur = null; while(head != null){ ListNode next = head.next; head.next = cur; cur = head; head = next; } return cur; } }
递归,每次减小一个
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseList(ListNode head) { // ListNode cur = null; // while(head != null){ // ListNode next = head.next; // head.next = cur; // cur = head; // head = next; // } // return cur; if (head == null || head.next == null) return head; ListNode newHead = reverseList(head.next); head.next.next = head; head.next = null; return newHead; } }
标签:tno span efi inpu style color 一个 node lis
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10345468.html