leetcode_206_反转链表

北城余情 提交于 2020-03-02 16:48:50

题目描述

在这里插入图片描述

分析

链表从头到尾遍历一遍,然后就得到结果,这样时间复杂度就会最低。 对链表进行反转,即将链表中的每个结点的上一个结点转为下一个结点,下一个结点转为上一个结点。用两个结点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;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!