zoukankan      html  css  js  c++  java
  • 面试题:反转链表

    题目描述:输入一个链表,反转链表后,输出新链表的表头。(画图容易理解)

    方法1:

    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null || head.next == null ) return head;
            ListNode pre = head;
            ListNode p = head.next;
            pre.next = null;
            ListNode nxt;
            while(p!=null){
                nxt = p.next;
                p.next = pre;
                pre = p;
                p = nxt;
            }
            return pre;
        }
    }

    方法2:

    public class Solution {
        public ListNode ReverseList(ListNode head) {
            if(head == null || head.next == null ) return head;
            ListNode p1 = head;
            ListNode p2 = head.next;
            ListNode p3 = p2.next;
            p1.next = null;
            while(p3!=null){
                p2.next = p1;
                p1 = p2;
                p2 = p3;
                p3 = p3.next;
            }
            //最后一个p3=null时p2的next没有设置
            p2.next = p1;
            return p2;
        }
    }
  • 相关阅读:
    敲七
    二维指针数组**p
    食物链(待解决)
    蛇行矩阵
    快速排序 QuickSort
    堆排序
    猪的安家
    百度语言翻译机
    HTML <base> 标签
    免费网络管理流量监控软件大比拼
  • 原文地址:https://www.cnblogs.com/Aaron12/p/9510488.html
Copyright © 2011-2022 走看看