链表逆序,java实现

 1 package com.cskaoyan.linkedlist;
 2 //反转数组
 3 public class LinkedListDemo2 {
 4     public static Node reverse(Node head){
 5         //若输入head是null 或者这个链表只有一个元素,不需要反转
 6         //null -->null
 7         //a,null-->a,null
 8         if(head==null||head.next==null) return head ;
 9         Node prev=null;
10         Node curr=head;
11         while(curr!=null){
12             Node nextNode=curr.next;
13             curr.next=prev;
14             prev=curr;
15             curr=nextNode;
16         }
17         return prev;
18     }
19     //使用递归使链表逆序
20     public static Node reverse1(Node head){
21         if (head == null || head.next == null) return head;
22         Node node=reverse1(head.next);
23         head.next.next=head;
24         head.next = null;
25         return node;
26     }
27     public static void main(String[] args) {
28         Node node = new Node(3);
29         node = new Node(2, node);
30         node = new Node(1, node);
31         Node head = reverse(node);
32         System.out.print(head.val + " ");
33     }
34 }
 1 package com.cskaoyan.linkedlist;
 2 
 3 public class Node {
 4     int val;
 5     Node next;
 6     public Node(int val){
 7         this.val=val;
 8     }
 9     public Node(int val,Node next){
10         this.val=val;
11         this.next=next;
12     }
13 }
原文地址:https://www.cnblogs.com/zhaoyuan72/p/11203940.html