反转一个单链表(Java)

看到反转链表,可能第一时间的想法便是遍历一遍这个单链表,然后把链表里的元素都取出来,放到一个数组里,然后逆置这个数组。这个想法是错的!!!

所以什么是反转链表呢?见下图:

 

反转一个单链表,我们需要的是改变这个链表内节点的指向。

反转链表第一步:

判断链表是否为空,如果链表为空,则直接返回null。

if (this.head == null) {    //没有节点
            return null;
        }

反转链表第二步:

判断链表是否只有一个节点,如果头结点的下一节点等于空,则说明该链表只有一个节点,即返回头结点。

  if (this.head.next == null) {   //只有一个节点
            return this.head;
        }

反转链表第三步:

//至少两个节点 
Node cur=this.head.next;
 this.head.next=null;
 while (cur!=null){
     Node curNext=cur.next;
     cur.next=head;
     this.head=cur;
     cur=curNext;
 }
   return head;

第三步详解如下:

链表反转后,它原本的头结点的下一节点就为空null了。但是不能在一开始就将头结点的下一节点置为空。因为将它置为空后,便失去了与链表本来head.next的联系;所以,我们定义一个cur记录头结点下一节点的位置;也就是说让head不动,将记录头结点下一节点位置的cur用头插法的方式插入到head的前边,在cur头插到head前再定义一个curNext记录cur的下一节点,使cur到了head前,也不会失去与后边节点的联系。当所有的链表都反转后,cur就会为空。

图解

 

 

 

 

 

完整代码如下:

 class Node{
    public int val;
    public Node next;  //类型是Node          null

    public Node(int val){
        this.val=val;

    }
} 

public class SingleLinkedList {
    public Node head;

 //反转链表
    //反转链表并不能使用逆置数组,需要改变链表元素的指向(使用头插法)
    public Node reverseList() {
        if (this.head == null) {    //没有节点
            return null;
        }
        if (this.head.next == null) {   //只有一个节点
            return this.head;
        }
        //至少有两个节点
        Node cur=this.head.next;
        this.head.next=null;
        while (cur!=null){
            Node curNext=cur.next;
            cur.next=head;
            this.head=cur;
            cur=curNext;
        }
        return head;
    }
}

  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
链表是指将链表中的节点顺序颠倒,即原来的头节点变为尾节点,原来的尾节点变为头节点。其中,头插法是一种常用的链表的方法。 在Java中,可以通过以下代码实现链表(使用头插法): ```java class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } } public class LinkedListReverse { public static ListNode reverse(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = null; while (head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } public static void main(String[] args) { // 创建一个示例链表:1 -> 2 -> 3 -> 4 -> 5 ListNode head = new ListNode(1); ListNode node2 = new ListNode(2); ListNode node3 = new ListNode(3); ListNode node4 = new ListNode(4); ListNode node5 = new ListNode(5); head.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; // 链表 ListNode reversedHead = reverse(head); // 输出后的链表:5 -> 4 -> 3 -> 2 -> 1 while (reversedHead != null) { System.out.print(reversedHead.val + " "); reversedHead = reversedHead.next; } } } ``` 以上代码中,`reverse`方法使用了头插法来链表。首先判断链表是否为空或只有一个节点,若是,则直接返回原链表。然后,通过循环遍历链表,每次将当前节点的`next`指针指向已部分的头节点,并更新新的头节点为当前节点。最后返回新的头节点即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值