import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode ReverseList (ListNode head) { ListNode current,last,next; if(head == null) return head; if(head.next == null) return head; if(head.next.next == null) { next = head.next; next.next = head; return next; } last = head; current = head.next; next = current.next; last.next = null; while(true){ //反转前两个节点 current.next = last; if(next.next == null) break; last = current; current = next; next = next.next; } next.next = current; return next; // write code here } }
last.next = null 需要写在循环前,不然只能输出三个值。
跳出循环的条件应该是next.next ==null ,而不是next==null,后者会报错,数组溢出。
应该处理好链表长度为0,1,2的情况。
总体思路为,每次反转交换last和current,同时需要next指向current.next,不然交换以后,没有指向原顺序下current后续节点的对象。当next.next == null说明已经处理到最后三个节点。倒数第三(last)和倒数第二个节点(current)可以用循环体中的方法处理,但倒数第一(next)和倒数第二个节点(next)放在循环外处理,因为终止条件只能是next.next==null, 而不是next==null。