zoukankan      html  css  js  c++  java
  • 反转单向链表

    思路一:定义三个节点分别为当前节点cur,前一个节点pre,后一个节点next
    我们需要当前节点由指向next转变为指向pre,并且我们必须先将下一个节点缓存起来否则改变了当前节点的指向
    我们无法继续遍历整个链表了。
    即步骤如下
    1 缓存当前节点的下一个节点 next=cur.next;
    2 将当前节点指向前一个节点 cur.next=pre;
    3 前一个节点后移一位,指向当前节点;pre=cur;
    4 当前节点后移一位 cur=next;
     
      public ListNode ReverseList(ListNode head) {
    
        ListNode cur = head;
    
        ListNode pre = null;
    
        ListNode next = null;
    
        while (cur != null) {
    
            next = cur.next;
    
            cur.next = pre;
    
            pre = cur;
    
            cur = next;
    
        }
    
        return pre;
    
        }
    思路二:借助于栈结构,首先遍历链表并且存储于栈中,接着 根据弹栈的顺序重新遍历栈并且更改每个
    节点的值  当然,在这里是通过改变每个节点的值来达到效果的 并没有 改变节点的 引用关系
     
     public ListNode ReverseList(ListNode head) {
    
        ListNode cur = head;
    
                ListNode pre = head;
    
                ListNode next = null;
    
               //借助栈的数据结构
    
                Stack stack = new Stack();
    
                while(cur!=null){
    
                    stack.push(cur.val);
    
                    cur=cur.next;
    
                }
    
                while(!stack.isEmpty()){
    
                    pre.val=(int) stack.pop();
    
                    pre=pre.next;
    
                }
    
                return head;
    
        }
    思路三 采用递归实现
    public ListNode ReverseList(ListNode head) {
    
            if (null == head || null == head.next) {  
    
              return head;  
    
                 }  
    
            ListNode reversedHead = ReverseList(head.next);  
    
            head.next.next=head;  
    
            head.next=null; 
    
            return reversedHead; 
    
                }
  • 相关阅读:
    C#特性
    C#继承
    对FileStream的几种属性和方法认识
    C# Parallel用法
    c#发布补丁
    WebApi接收接收日期格式参数时,日期类型(2019-10-08T16:00:00.000Z)后台接收时间少8小时问题
    c# 基于WebApi的快速开发框架FastFramework
    c# webapi结合swagger的使用
    windows服务autofac注入quartz任务
    c# autofac结合WebApi的使用
  • 原文地址:https://www.cnblogs.com/winAlaugh/p/5348782.html
Copyright © 2011-2022 走看看