[java]反转单项链表,用O(n)时间和O(1)空间

链表数据结构

public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int x) {
        val = x;
    }
}

反转代码

public ListNode reverse(ListNode head) {
    ListNode p;
    ListNode tmp = head.next;
    head.next = null;
    while(tmp != null) {
        p = tmp;
        tmp = tmp.next;
        p.next = head;
        head = p;
    }
    return head;}
时间: 2024-08-03 21:23:19

[java]反转单项链表,用O(n)时间和O(1)空间的相关文章

java实现单项链表(复制,自己总结的在下一篇)

一.单向链表的结构. (1).首先节点的结构,其中包含本节点内容,以及需要指向下一个节点. Java代码 private static class Entry<E>{ E e; Entry<E> nextEntry; public Entry(E e,Entry<E> nextEntry){ this.e=e; this.nextEntry=nextEntry; } } private static class Entry<E>{ E e; Entry<

Java反转单链表(code)

主要是面试中可能会经常碰上该类似操作,尤其是稍大点公司,面试官可能并不在乎你能不能搞定该题,但是这类型题目最是能体现程序员的思维状态 ---一个迷糊头脑的程序员 怎能立志改变这个世界 /** * @author luochengcheng * 定义一个单链表 */ class Node { //变量 private int record; //指向下一个对象 private Node nextNode; public Node(int record) { super(); this.record

【LeetCode-面试算法经典-Java实现】【092-Reverse Linked List II(反转单链表II)】

[092-Reverse Linked List II(反转单链表II)] [LeetCode-面试算法经典-Java实现][所有题目目录索引] 原题 Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->

反转单向链表(JAVA)

在微博看到,有人说8个应届毕业生没有人写出o(1)空间复杂度,o(n)时间复杂度的反转单向链表. (不是我自己想的) public void reverseList(ListNode head) { ListNode newHead = null; while(head != null) { ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; } 自己也想了很

Linked List Cycle leetcode II java (寻找链表环的入口)

题目: Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up: Can you solve it without using extra space? 题解: 这个连同I都是很经典的题啦,刷CC150时候就折磨了半天. 其实就推几个递推公式就好..首先看图(图引用自CC150): 从链表起始处到环入口长度为:a,从环入口到Faster和Sl

Java 实现单链表反序

//单链表反序 public class SingleLinkedListReverse { public static void main(String[] args) { Node head = new Node(0); Node temp = null; Node cur = null; for (int i = 1; i <= 10; i++) { temp = new Node(i); if (i == 1) { head.setNext(temp); } else { cur.set

数据结构和算法之单向链表六:链表的反转以及链表节点的删除

在前面介绍了关于链表的一系列问题,这里我们在介绍一下关于单向链表的反转这个比较具有代表性的算法.在进行反转的时候一定要记住多画图,多去理解在链表进行反转的时候它对于地址的改变,这和数组的数据对换具有很大的不一致. public Node reverseList(Node head){ //判断链表是否为空或者只有一个节点 if(head == null || head.next == null){ return head; } //准备三个节点 Node next = null;//保存当前节点

数据结构——反转单链表

最近看了<剑指offer>这本书,遇到了一个问题:反转链表 题目:定义一个函数,输入一个链表的头结点,反转该链表并输出反转后的链表的头结点. 链表结点定义如下: struct ListNode { int _data; ListNode * _pNext; }; 解决方案如下: ListNode * ReverseList(ListNode * pHead) { ListNode * pRevesedHead = nullptr;//反转后的头结点 ListNode * pNode = pHe

题目:输入一个链表的头结点,反转该链表,并返回反转后链表的头结点。

题目:输入一个链表的头结点,反转该链表,并返回反转后链表的头结点.链表结点定义如下: struct ListNode { int       m_nKey; ListNode* m_pNext; }; c语言实现 /* File : rlink.c Author : Date : 2015/4/4 platform : windows7 x86_64 version : 1.0 Function : 反转一个链表 */ #include <stdio.h> #include <stdli