逆转链表

一:idea能跑起来的代码

public class Reverse {
    public static void main(String[] args){
        ListNode node1=new ListNode();
        ListNode node2=new ListNode();
        node1.setVal(1);
        node1.setNext(node2);
        node2.setVal(2);
        ListNode listNode=reverseList(node1);
        System.out.println(listNode);

    }
    public static ListNode reverseList(ListNode head) {
        if (head.getNext() == null || head == null){
            return head;
        }
        ListNode newdata = reverseList(head.getNext());
        //这个递归,返回值只是为了控制返回的是最后一个节点
        //然后通过递归通过栈的特性,这里就是让它可以从最后一个节点开始把自己的子节点的子节点改成自己
        //自己的子节点改为null
        head.getNext().setNext(head);
        head.setNext(null);
        return newdata;
    }
}

class ListNode {
    private int val;
    private ListNode next = null;

    public ListNode getNext(){
        return next;
    }
    public void setNext(ListNode node) {
        this.next = node;
    }
    public int getVal() {
        return val;
    }
    public void setVal(int val){
        this.val=val;
    }
}

 

 

二:牛客网能跑起来的代码

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
         // 判断链表为空或长度为1的情况
        if(head == null || head.next == null){
            return head;
        }
        ListNode pre = null; // 当前节点的前一个节点
        ListNode next = null; // 当前节点的下一个节点
        while( head != null){
            next = head.next; // 记录当前节点的下一个节点位置;
            head.next = pre; // 让当前节点指向前一个节点位置,完成反转
            pre = head; // pre 往右走
            head = next;// 当前节点往右继续走
        }
        return pre;
    }
}

 

posted @ 2021-03-01 10:33  姚春辉  阅读(77)  评论(0编辑  收藏  举报