
Reverse a singly linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class { public ListNode reverseList(ListNode head) { if(head==null||head.next==null) return head; LinkedList<ListNode> temp=new LinkedList<>(); while(head!=null) { temp.add(head); head=head.next; } ListNode tempNode=temp.remove(temp.size()-1); ListNode resultNode=tempNode; while(!temp.isEmpty()) { tempNode.next=temp.remove(temp.size()-1); tempNode=tempNode.next; } tempNode.next=null; return resultNode; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
public class {
public ListNode reverse(ListNode head) { if(head==null||head.next==null) return head; ListNode cur=head.next; head.next=null; while(cur!=null) { ListNode temp=cur.next; cur.next=head; head=cur; cur=temp; } return head; } }
|
近期评论