Reverse a singly linked list.
Hint:
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; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if(head==null) return null; if(head.next==null)return head; ListNode p=head.next; ListNode n=reverseList(p); head.next=null; p.next=head; return n; } }
非递归,迭代的办法:
if(head == null || head.next == null) return head; ListNode current = head.next; head.next = null; while(current ! = null){ ListNode temp = current.next; current.next = head; head = current; current = temp.next; } return head;
时间: 2024-10-11 08:18:03