分享

leetcode_206_反转链表

 印度阿三17 2020-03-02

题目描述

在这里插入图片描述

分析

链表从头到尾遍历一遍,然后就得到结果,这样时间复杂度就会最低。 对链表进行反转,即将链表中的每个结点的上一个结点转为下一个结点,下一个结点转为上一个结点。用两个结点preNode和nextNode来分别记录原链表中的上一个结点和下一个结点,然后进行转换,循环执行,即可得到结果。

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null)
            return head;
        ListNode nextNode=null,preNode=null;
        while(head!=null){
            nextNode=head.next;
            head.next=preNode; 
            preNode=head;
            head=nextNode;
        }
        return preNode;
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多