【leetcode】【206】Reverse Linked List

来源:互联网 发布:linux命令cat和grep 编辑:程序博客网 时间:2024/04/27 18:20

一、问题描述

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

二、问题分析

这道题,最先想到的是迭代的方式。而迭代又有两种方式:①保持从头访问过的元素先对位置不变,只改变指针的方向,头结点需要单独处理;②指针方向不变,改变元素的位置,即每访问一个新的元素,就把新元素插到头上;

递归的方法其实是从链表的最后边依次改变指针的方向。

三、Java AC代码

迭代①

public ListNode reverseList(ListNode head) {        if (head==null || head.next == null) {return head;}        ListNode pre = head;        ListNode cur = head.next;        pre.next = null;        ListNode nxt = null;        while(cur!=null){        nxt = cur.next;        cur.next = pre;        pre = cur;        cur = nxt;        }        return pre;    }


迭代②

public ListNode reverseList(ListNode head) {        if (head==null || head.next == null) {return head;}        ListNode pivot = head;        ListNode frontier = null;        while(pivot.next!=null){            frontier = pivot.next;            pivot.next = frontier.next;            frontier.next = head;            head = frontier;        }        return head;    }


递归

public ListNode reverseList(ListNode head) {        if(head == null ||head.next == null){            return head;        }                ListNode root = reverseList(head.next);                head.next.next = head;        head.next = null;        return root;    }


0 0
原创粉丝点击