标签:
https://leetcode.com/problems/reverse-linked-list/
Reverse a singly linked list
1 public class Solution { 2 public static ListNode reverseList(ListNode head) { 3 if(head==null) return null; 4 ListNode newHead=new ListNode(0); 5 ListNode prehead=head.next; 6 while(true){ 7 head.next=newHead.next; 8 newHead.next=head; 9 if(prehead==null) break; 10 head=prehead; 11 prehead=head.next; 12 } 13 return newHead.next; 14 } 15 public static class ListNode { 16 int val; 17 ListNode next; 18 ListNode(int x) { 19 val = x; 20 } 21 } 22 public static void main(String[]args){ 23 ListNode[]node=new ListNode[4]; 24 for(int i=0;i<node.length;i++){ 25 node[i]=new ListNode(i); 26 } 27 node[0].next=node[1]; 28 node[1].next=node[2]; 29 node[2].next=node[3]; 30 ListNode head=reverseList(node[0]); 31 while(head!=null){ 32 System.out.println(head.val); 33 head=head.next; 34 } 35 } 36 }
标签:
原文地址:http://www.cnblogs.com/qq1029579233/p/4480205.html