链表逆序,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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值