15 反转链表ReverseList

输入一个链表,反转链表后,输出新链表的表头。

 1 import java.util.*;
 2 /*
 3 public class ListNode {
 4     int val;
 5     ListNode next = null;
 6 
 7     ListNode(int val) {
 8         this.val = val;
 9     }
10 }*/
11 public class Solution {
12     public static ListNode ReverseList(ListNode head) {
13         ListNode nextnode = null;
14         ListNode prenode = null;
15         while(head!=null){
16             nextnode = head.next;
17             head.next = prenode;
18             prenode = head;
19             head = nextnode;
20         }
21         return prenode;
22     }
23     public static void main(String [] args){
24         Scanner sc = new Scanner(System.in);
25         System.out.println("请依次输入链表");
26         ListNode head = null;
27         if(sc.hasNext())    head = new ListNode(sc.nextInt());
28         ListNode temp = head;
29         while(sc.hasNext()){
30             temp = new ListNode(sc.nextInt());
31             temp = temp.next;
32         }
33         temp.next = null;
34         ReverseList(head);
35     }
36 }

主要是三个指针在操控着反转的链表,A - -> B - -> C - -> D - -> E - -> F

16             nextnode = head.next;
17             head.next = prenode;
18             prenode = head;
19             head = nextnode;

head一开始指向A

nextnode指向了B   

A指向了prenode也就是空   A和B之间的链断开

head代表的A给了prenode,现在prenode就是A了,成功实现了A的反转出来

在将B给了head,重新循环就OK

posted @ 2019-07-01 10:05  淡如水94  阅读(561)  评论(0)    收藏  举报