链表反转-Java

 第一种方法: 借助栈的先进后入原则

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode ReverseList (ListNode head) {
        // write code here
        if(head ==null || head.next ==null){
            return head ;
        }

        Stack<ListNode> ss = new Stack();
        while(head!=null){
            ss.add(head);
            head = head.next ;
        }

        ListNode res = ss.pop();
        ListNode cur = res ;
        while(!ss.isEmpty()){
           ListNode node =  ss.pop();
           cur.next = node;
           cur = cur.next ;
        }
        cur.next = null ;
        return res ;
    }
}

第二种:使用头插法:

虚拟一个头结点,尾结点 ;

head  >>  2 >> 3 >>4>> tail

例如上面的链接,如果需要再head插入1,则首先需要获取原先的head.next 缓存temp,然后让head 指向 1 即 head.next = new Node() ; 然后让新增节点的next指向temp 即 new Node().next = temp ; 就可以完成头插法。所以所谓的头插法反转就是新增了一个新的链表,然后遍历原先的链表,每次使用头插法插入到新的链表即可;

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    public ListNode ReverseList (ListNode head) {
        // write code here
        if(head == null || head.next ==null){
            return head ;
        }

        ListNode newHead = new ListNode(-1);
        ListNode cur = head ;
        while(cur!=null){
            ListNode next = cur.next ;
            addToHead(newHead,cur);
            cur =next;
        }

        return newHead.next;

    }

    public void addToHead(ListNode newHead ,ListNode node){
        // head >> 2 >>3 >> tail 新增1 
        ListNode temp = newHead.next ; 
        newHead.next = node ;
        node.next = temp ;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值