zoukankan      html  css  js  c++  java
  • 反转链表

    package com.lkr.dataStructure.linkedlist;

    import java.util.LinkedList;

    //反转单链表
    public class ReverseList {

    public static void main(String[] args){
    ListNode linkNode1 = new ListNode(1);
    ListNode linkNode2 = new ListNode(2);
    ListNode linkNode3 = new ListNode(3);
    ListNode linkNode4 = new ListNode(4);
    ListNode linkNode5 = new ListNode(5);
    ListNode linkNode6 = new ListNode(6);
    linkNode1.next = linkNode2;
    linkNode2.next = linkNode3;
    linkNode3.next = linkNode4;
    linkNode4.next = linkNode5;
    linkNode5.next = linkNode6;
    System.out.println("链表为: ");
    printList(linkNode1);
    System.out.println(" 链表反转后为: ");
    //遍历法
    //reverseList(linkNode1);
    //递归法
    reverseList3(linkNode1);
    //反向输出链表
    // reservePrt(linkNode1);
    printList(linkNode6);

    }

    //打印链表数据
    public static void printList(ListNode node){
    System.out.print(node.data);
    if(node.next != null){
    printList(node.next);
    }

    }

    //遍历法
    public static ListNode reverseList(ListNode head){
    ListNode pReversedHead =null; //反转后的单链表头节点
    ListNode pNode = head; //定义pNode指向head
    ListNode pPre = null; //定义存储前一个节点
    while (pNode != null){
    ListNode pNext = pNode.next; //定义pNext指向pNode下一个节点
    if(pNext != null){ //如果pNode下一个节点为空,则pNode即为结束
    pReversedHead = pNode;
    }
    pNode.next = pPre; //修改pNode指针域指向pPre
    pPre = pNode; //复制pNode到pPre
    pNode = pNext; //将pNode的下一个节点复制给pNext
    }
    return pReversedHead;
    }

    //递归实现

    public static ListNode reverseList3(ListNode pHead){
    if(pHead==null || pHead.next == null){ //如果没有结点或者只有一个结点直接返回pHead
    return pHead;
    }
    ListNode pNext = pHead.next; //保存当前结点的下一结点
    pHead.next = null; //打断当前结点的指针域
    ListNode reverseHead = reverseList3(pNext); //递归结束时reverseHead一定是新链表的头结点
    pNext.next = pHead; //修改指针域
    return reverseHead;
    }

    //反向输出链表
    public static void reservePrt(ListNode node){
    if(node != null){
    reservePrt(node.next);
    System.out.print(node.data+" ");
    }
    }

    }

  • 相关阅读:
    Vue3.0实战项目
    Vue 笔试题(做对九题即可成为前端懂王)
    CSS 响应式布局---Grid 布局
    CSS快速提升技巧(一)
    前端骨架屏
    Python学习29
    Python学习28
    Python学习27
    Python学习26
    Python学习25
  • 原文地址:https://www.cnblogs.com/turningli/p/10389869.html
Copyright © 2011-2022 走看看