反转链表

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

个人思路:一个一个断链,断链之间用指针记录下。

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode ReverseList(ListNode head) {
12         if(head==null)
13             return null;
14         else if(head.next==null)
15             return head;
16         else{
17             ListNode p = head.next;
18             ListNode temp = head;
19             head = head.next;
20             temp.next = null;
21             while(head.next!=null){
22                 head = head.next;
23                 p.next = temp;
24                 temp = p;
25                 p = head;
26             }
27             head.next = temp;
28             return head;
29         }
30 
31     }
32 }
原文地址:https://www.cnblogs.com/haq123/p/12154784.html