链表反转

将单链表的链接顺序反转过来

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

使用两种方式解题

public class ReverseList {
    static class ListNode{
        int val;
        ListNode next;

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
   //迭代
    public static ListNode iterate(ListNode head){
        ListNode prev=null,next;
        ListNode curr = head;
        while (curr != null){
            next = curr.next;//将下一个节点指针保存到next变量
            curr.next=prev;//将下一个节点的指针指向prev
            prev = curr;//准备处理下一个节点,将curr赋值给prev
            curr = next;//将下一个节点赋值为curr,处理一个节点
        }
        return prev;
    }

    //递归
    public static ListNode recursion(ListNode head){
        if (head==null || head.next==null){
            return head;
        }
        ListNode new_head = recursion(head.next);
        head.next.next = head;
        head.next = null;

        return new_head;
    }

    public static void main(String[] args) {
        ListNode node5 = new ListNode(5,null);
        ListNode node4 = new ListNode(4,node5);
        ListNode node3 = new ListNode(3,node4);
        ListNode node2 = new ListNode(2,node3);
        ListNode node1 = new ListNode(1,node2);
        ListNode prev = iterate(node1);
        System.out.println(prev);
    }
上一篇:链表中的倒数第k个节点,回文链表


下一篇:动态规划问题(十五)不含连续1的非负整数