算法:反转链表

问题:

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

解决:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

 //1、利用链表反转
class Solution {
    public ListNode reverseList(ListNode head) {
        // 使用两个链表进行
        ListNode pre=null;
        ListNode cur=head;
        while(cur!=null){
            ListNode next=cur.next;     //将cur剩下结点存到next中

            cur.next=pre;              //cur.next指向pre
            pre=cur;                    //将pre指向cur                       这几步完成了将cur中的结点以反序赋给pre
            cur=next;                   //将原本剩下的结点重新还给cur
        }
        return pre;
    }
}
//反转该链表并输出反转后链表的头节点



//2、使用栈解决
class Solution{
    public ListNode reverseList(ListNode head){
        //利用栈进行反转
        if(head==null) return head;
        // 1.首先要将链表中的结点放到栈中
        Stack<ListNode> stack=new Stack<ListNode>();
        ListNode cur=head;
        while(cur!=null){
            stack.push(cur);
            cur=cur.next;
        }
        // 2。再将栈中的结点拿出
        ListNode pre=stack.pop();
        ListNode nex=pre;
        nex.next=null;                  //创建两条相交链表

        while(!stack.empty()){
            nex.next=stack.pop();           //让nex.next不断的指向新结点,将结点添加到相交链中,然后将nex向后移动
            nex=nex.next;
            nex.next=null;    
        }
        return pre;
    }
}

// 3、递归!!
class Solution{
    public ListNode reverseList(ListNode head){
        if(head==null||head.next==null) return head;
        ListNode newHead= reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return newHead;
    }
}

总结

  • 使用栈的想法最简单,但是要注意怎么将栈中的单个结点正确的链接到链表上
  • 递归想法最抽象,需要注意避免出现环,递归结束条件
posted @   new_monkey  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示