反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。
 1 *
 2  * 题目描述
 3  * 输入一个链表,反转链表后,输出新链表的表头。
 4  */
 5 
 6 public class Main15 {
 7 
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         ListNode head = new ListNode(0);
11         ListNode[] p = new ListNode[6];
12         for(int i=0;i<p.length;i++) {
13             p[i] = new ListNode(i+1);
14             if(i>0) {
15                 p[i-1].next = p[i];
16             }else {
17                 head = p[0];
18             }
19             //{1,2,3,4,5,6}
20         }
21         ListNode result = Main15.ReverseList(head);
22         System.out.println(result.val);
23     }
24     
25     public static class ListNode {
26         int val;
27         ListNode next = null;
28 
29         ListNode(int val) {
30             this.val = val;
31         }
32     }
33     
34     public static ListNode ReverseList(ListNode head) {
35         if (head == null) {
36             return null;
37         }
38         
39         ListNode next = null; //当前节点的后一个节点
40         ListNode pre = null; //当前节点的前一个节点
41         while (head != null) {
42             next = head.next;
43             head.next = pre;
44             pre = head;
45             head = next;
46         }
47         return pre;
48     }
49 
50 }

个人建议,自己画图走两个循环就很清楚了

原文地址:https://www.cnblogs.com/strive-19970713/p/11083011.html