首页 > 代码库 > 反转链表

反转链表

 1 package com.algorithm;
 2 
 3 //输入一个链表,反转链表后,输出链表的所有元素。
 4 public class ReverseListMe {
 5     
 6     public ListNode ReverseList(ListNode head) {
 7         //运行时间:36ms 占用内存:528k
 8         if(head == null) {
 9             return head;
10         }
11         if(head.next == null) {
12             System.out.println(head.val);
13             return head;
14         }
15          ListNode front = head;//前一个
16          ListNode back = head.next;//后一个
17          ListNode guard = back.next;//第三个
18          front.next = null;//将最后一个赋值为null
19          while(back != null) {
20              back.next = front;//把第二项的next 赋值为front
21              front = back;
22              back = guard;//将guard 赋值给front
23              if(guard != null)
24               guard = guard.next;//将guade的next赋值给guard
25          }
26          head = front;
27          while(front != null) {
28              System.out.println(front.val);
29              front = front.next;
30          }
31          return head;
32     }
33     public static void main(String[] args) {
34          ListNode la = new ListNode(1);
35           ListNode lb = new ListNode(2);
36           ListNode lc = new ListNode(3);
37           la.next = lb;
38           lb.next = lc;
39           lc.next = null;
40           new ReverseListMe().ReverseList(la);
41     }
42     /*class ListNode {
43         int val;
44         ListNode next = null;
45         ListNode(int val) {
46             this.val = val;
47         }
48     }*/
49 }
1 ListNode pre = null;   
2 ListNode next = null;    
3 while (head != null) {        
4     next = head.next;        
5     head.next = pre;        
6     pre = head;        
7     head = next;    
8 }    
9     return pre;

 

 

反转链表