反转单链表(Java)

题目描述:本题源于leetcode上面试题26

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路:

该题有两种效率比较好的解法:

1.头插法:这是一种常见的反转单链表的解法---》先定义一个新的头节点,然后让原始链表从前往后遍历单链表,依次头插到新的链表头。这样就得到了反转后的链表。

2.三引用法:

  • 正如该方法的名字,先定义三个节点的引用;分别是:pre、cur、curNext。pre一开始为null,cur指向链表头,curNext指向cur.next;
  • 从cur开始循环遍历链表,遍历条件为:cur !=null;每次遍历让cur指向pre,curNext作为临时节点保存cur;
  • 返回新节点即可

注意:一开始一定需要让链表头节点指向null,否则链表会形成环,这是本人踩过的坑。

代码:

class Solution {
    //方法一:头插法

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

        ListNode cur=head;
        //先定义一个新的头
        ListNode newHead=null;
       while(cur!=null)
       {
           ListNode now=cur;
            cur=cur.next;     
          
               now.next=newHead;
               newHead=now;
       }
        
        return newHead;
    }
}
class Solution {
    //方法二:三指针法

    public ListNode reverseList(ListNode head) {
        if(head==null ||head.next==null)
        {
            return head;
        }
        ListNode pre=null;
        ListNode cur=head;
        ListNode newHead=null;
        while(cur!=null)
        {
            ListNode last=cur.next;
            if(last==null)
            {
                newHead=cur;
            }
            cur.next=pre;
            pre=cur;
            cur=last;            
        }        
        return newHead;
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
单链表反转是指将链表中的节点顺序颠倒,即原来的头节点变为尾节点,原来的尾节点变为头节点。其中,头插法是一种常用的反转单链表的方法。 在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`指针指向已反转部分的头节点,并更新新的头节点为当前节点。最后返回新的头节点即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值