public class Solution { /** * 思路: 将当前currentListNode的next指针指向preListNode * 注意点: 记录下currentListNode的nextNode, 待上面的操作完成, 更改变量引用, 否则下次循环没有currentListNode * @param head * @return */ public ListNode reverseList(ListNode head) { // 非空判断: 1, 如果head参数是null, 此时链表中无元素; 2, 如果head.next为null,此时链表只有一个元素 if(head==null||head.next ==null){ return head; } ListNode preNode = null; ListNode thisNode = head; ListNode nextNode = null; while (thisNode != null) { //1, 记录下nextNode: 修改thisNode的next指针钱 nextNode = thisNode.next; //2, 修改next指针指向: 修改当前节点的next指针指向preNode thisNode.next = preNode; //3, 更改变量引用: 为下一个循环做准备 preNode = thisNode; thisNode = nextNode; } // 返回preNode: 这时的preNode肯定不是null, 是循环结束的最后一个元素 return preNode; }}
class ListNode { int val; ListNode next;
ListNode(int x) { val = x; }}
评论