首页 > 其他 > 详细

链表的翻转

时间:2019-08-06 17:20:09      阅读:52      评论:0      收藏:0      [点我收藏+]
package Struct;

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

    public ListNode(int val) {
        this.val = val;
    }
}
package offer;

import Struct.ListNode;

/**
 * 
 * 
 * 链表反转输出链表的头
 *  
 *
 *
 * @author 爱不会绝迹
 *
 */
public class Problem05 {
        /**
          * 链表的反转可以利用头插法将链表的节点顺序倒置
          */
    public static ListNode ReverseList(ListNode head) {
        ListNode h = new ListNode(-1);
        ListNode p = head;
        ListNode p1 = p;
        while(p1 != null){
            p1 = p1.next;
            p.next = h.next;                
            h.next = p;    
            p = p1;
        }
        return h.next;
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode p = null;
        for(int i = 5;i >1;i --){
            p = new ListNode(i);
            p.next = head.next;
            head.next = p;
        }
        ReverseList(head);
    }
}

 

链表的翻转

原文:https://www.cnblogs.com/yangenyu/p/11310244.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!