剑指offer:输入一个链表,反转链表后,输出新链表的表头。

代码思路:
使用头插法插入:

当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点

需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2

即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了

所以需要用到pre和next两个节点

1->2->3->4->5

1<-2<-3 4->5

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null)
            return null;
        ListNode pre = null; //当前结点的前一个结点
        ListNode last = null; //当前结点的后一个结点
        while(head != null)
        {
            last = head.next; 
            //先保存head.next信息,不然会丢失。若先head.next=pre,则head.next信息丢失
            head.next = pre;  //
            
            pre = head;
            head = last;//pre和head各向后移动一位
            
        }
        return pre;

    }
}

思路二:利用栈的特性

import java.util.Stack;
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)//若链表为空或者只有一个结点
            return head;
        Stack<ListNode> stack = new Stack<ListNode>();
        while(head!=null && head.next != null)
        {
            stack.push(head);
            head = head.next;
        }

        ListNode dummylast = stack.peek();//dummylast是倒数第二个结点
        ListNode lastnode = dummylast.next;//取最后一个元素作为头结点
        ListNode newHead = lastnode;
        while(!stack.isEmpty())
        {
            lastnode.next = stack.peek();
            lastnode = lastnode.next;
            stack.pop();
        }
        lastnode.next = null;//最后一个结点应该置位null
        return newHead;

    }
}

思路三:递归

import java.util.Stack;
public 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;

    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值