美文网首页
链表逆序的两种方法(java)

链表逆序的两种方法(java)

作者: 站在埃菲尔铁塔上看风景 | 来源:发表于2017-09-22 15:28 被阅读0次

    public class ListNode {

    int val;

    ListNode next;

    public ListNode(int val) {

    this.val = val;

    }

    }

    1.用迭代的方法反转链表(iteratively)

    class Solution {

    public ListNode reverseList(ListNode head) {

    if (head == null) {

    return null;

    }

    ListNode dummy = new ListNode(0);

    dummy.next = head;

    ListNode pre = dummy.next;

    ListNode start = pre.next;

    ListNode then = start.next;

    while (then != null) {

    start.next = then.next;

    then.next = pre.next;

    pre.next = then;

    then = start.next;

    }

    return dummy.next;

    }

    }

    2.用递归的方法反转链表(recursively)

    class Solution {

    public ListNode reverseList(ListNode head){

    if (head.next == null || head == null) {

    return head;

    }

    ListNode nextNode = head.next;

    ListNode last = reverseList(nextNode);

    nextNode.next = head;

    head.next = null;

    return last;

    }

    }

    相关文章

      网友评论

          本文标题:链表逆序的两种方法(java)

          本文链接:https://www.haomeiwen.com/subject/zqgzsxtx.html