java算法题-反转链表

直接上代码,因为是在线编辑器,很多package都省略了,主要是看关键代码;通过递归方式反转链表

 

```java

public class HelloWorld{

  public static void main(String []args){
    ListNode node5 = new ListNode(5,null);
    ListNode node4 = new ListNode(4,node5);
    ListNode node3 = new ListNode(3,node4);
    ListNode node2 = new ListNode(2,node3);
    ListNode node1 = new ListNode(1,node2);
    
    printListNode(node1);
    
    ListNode res = reverseList(node1);
    System.out.println();
    System.out.print("reverser result is:");
    printListNode(res);
 }
 
 
 
 private static void printListNode(ListNode node){
     while(node!=null){
         System.out.print(node.val +(node.next!=null ? "->":""));
         node = node.next;
     }
 }
 
public static class ListNode{
    public int val;
    public ListNode next;
    public ListNode(int val,ListNode next){
        this.val = val;
        this.next = next;
    }
}
 
private static ListNode reverseList(ListNode head){
    
    if(head ==null || head.next==null) return head;
    
    ListNode listRes = reverseList(head.next);
    
    head.next.next = head;
    head.next = null;
    
    return listRes;
}

}



补充:迭代法

```java

    public static ListNode diedai(ListNode head){
        ListNode preNode=null,next,curNode;        
        curNode = head;
        while(curNode!=null){
            next = curNode.next;
            curNode.next = preNode;
            preNode = curNode;
            curNode = next;
        }
        return preNode;
    }
```java

### 运行结果:
1->2->3->4->5
reverser result is:5->4->3->2->1
posted @   明&天  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示