3.5 反转链表

方法1:构造一个新链表,从旧链表依次拿到每个节点,创建新节点添加到新链表头部,完成后即是倒序的。

定义一个ListNode类(一般题目中会有)

package org.example;

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int val,ListNode next){
        this.val=val;
        this.next=next;
    }

    @Override
    public String toString(){
        StringBuilder sb=new StringBuilder(64);
        sb.append("[");
        ListNode p=this;
        while (p!=null){
            sb.append(p.val);
            if(p.next!=null){
                sb.append(",");
            }
            p=p.next;
        }
        sb.append("]");
        return sb.toString();
    }

}

代码:

 public ListNode reverseList(ListNode o1){
        ListNode n1=null;
        ListNode p=o1;
        while(p!=null){
           n1= new ListNode(p.val,n1);
            p=p.next;
        }
        return n1;
    }

测试样例:

   public static void main(String [] args){
        ListNode o5=new ListNode(5,null);
        ListNode o4=new ListNode(4,o5);
        ListNode o3=new ListNode(3,o4);
        ListNode o2=new ListNode(2,o3);
        ListNode o1=new ListNode(1,o2);
        System.out.println(o1);
        ListNode n1=new E01Leetcode206().reverseList(o1);
        System.out.println(n1);

    }

方法二

构建新链表,就链表头部移除节点,添加到新链表头部,新链表是倒序的。

题目中未提供节点外层的容器类,自己提供一个

方法三:递归

    public ListNode reverseList(ListNode head){
        if(head==null||head.next==null){
            return head;
        }
        ListNode last=reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return last;
    }

方法四:

public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode o1=head;
        ListNode o2;
        ListNode n1=o1;

        while((o2=o1.next)!=null){
            o1.next=o2.next;
            o2.next=n1;
            n1=o2;
        }
        return n1;
    }

方法五:

 public ListNode reverseList(ListNode o1){
        if(o1==null||o1.next==null){
            return o1;
        }
        ListNode n1=null;
        while(o1!=null){
        ListNode o2=o1.next;
           o1.next=n1;
           n1=o1;
           o1=o2;
        }
        return n1;
        
  }

你可能感兴趣的:(链表,javascript,数据结构)