单向链表反转

题目

给定如下链表的节点定义:

// C语言定义节点
struct LinkNode
{
	int value;
	LinkNode* next;
};

比如有一个链表是这样的,1->2->3->4->5,反转后成为 5->4->3->2->1。请实现函数

LinkNode* Reverse(LinkNode* header);

分析

实现链表反转,我们需要从第二个节点开始遍历,将当前节点的 next 指向前一个节点。这里需要注意的是,该变当前节点的 next 时,需要提前保存 next,不然遍历就会中断。

时间复杂度 O(n);
空间复杂度 O(1)。

实现

以Java的方式实现

// 节点类
    static class Node{
        Node next;
        int value;
        Node(int value){
            this.value = value;
        }
    }

    // 翻转链表
    public static Node reverse(Node node){
        // 如果是空或者只有一个元素直接返回
       if (node == null || node.next == null){
           return node;
       }
       // 实现链表反转,我们需要从第二个节点开始遍历,将当前节点的 next 指向前一个节点。这里需要注意的是,该变当前节点的 next 时,需要提前保存 next,不然遍历就会中断。
        // 时间复杂度 O(n);空间复杂度 O(1)。

        // 第一个节点
       Node pre = node;
       // 第二个节点
       Node current = node.next;
       // 第一个节点变成最后一个节点后,next为null
       pre.next = null;
       while (current != null){
           // 保存当前节点的下一个节点
           Node temp = current.next;
           // 把当前节点的下一个节点指向前一个节点
           current.next = pre;
           // 把当前的节点的值给前一个节点
           pre = current;
           // 把下一个节点的值给当前节点
           current = temp;
       }
       return pre;
    }

    //  打印链表
    public static void printLinkedList(Node node){
        if (node == null){
            System.out.println("The LinkedList is null");
            return;
        }
        do {
            if (node.next != null){
                System.out.print(node.value+"->");
            }else {
                System.out.print(node.value);
            }
            node = node.next;
        }while (node !=null);
    }

    // 构造链表
    public static Node createLinkedList(int i){
        Node header = null;
        Node current = null;
        for (int j = 0; j < i; j++) {
            Node node = new Node(j+1);
            if (header == null){
                header = node;
                current = header;
            }else {
                current.next = node;
                current = node;
            }
        }
        return header;
    }

验证

public static void main(String[] args) {
        Node node = createLinkedList(5);
        printLinkedList(node);
        System.out.println();
        Node reverseNode = reverse(node);
        printLinkedList(reverseNode);
    }

结果

"D:\IntelliJ IDEA 2019.3.1\jbr\bin\java.exe" "-javaagent:D:\IntelliJ IDEA 2019.3.1\lib\idea_rt.jar=53516:D:\IntelliJ IDEA 2019.3.1\bin" -Dfile.encoding=UTF-8 -classpath D:\IdeaProjects\Arithmetic\out\production\Arithmetic Main
1->2->3->4->5
5->4->3->2->1
Process finished with exit code 0

经典算法——单向链表反转

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值