反转单链表(只可以遍历一次)

本文详细介绍了两种单链表反转的方法:通过定义三个节点进行反转及利用头插法实现。文章提供了完整的代码示例,深入解析了每一步操作,帮助读者理解单链表反转的原理和实践。

反转单链表的意思就是
原来单链表的值为1>2>3>4>5
反转之后会变成5>4>3>2>1
我们需要了解的是一定不能重新创建一个单链表来进行反转,因为那样太简单了,并且是极度浪费空间和资源的,有时候实在oj上跑不过的
首先我将单链表的有关代码放在这里

import com.sun.deploy.net.proxy.ProxyUnavailableException;

class Node {//节点类

    public int data;
    public Node next;

    public Node() {

    }

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
public class SingleLinkedList {
    //单链表本身是一种类
    //由节点来构成单链表,

    public Node head;//头节点

    public SingleLinkedList() {
        this.head = null;
    }

    //头插法
   public void addFirst(int data) {
       Node node = new Node(data);
       if(this.head == null) {
           this.head = node;
           return;
       }
       node.next = this.head;
       this.head = node;
   }
    //打印单链表
   public void display() {
    Node cur = this.head;
    if(this.head == null) {
	 System.out.println("没有存放数据")}
    while (cur != null) {
	 System.out.print(cur.data + " ");
         cur = cur.next;
    }
   }
	  
 public void display2(Node newHead) {
    Node cur = newHead;
    if(this.head == null) {
        System.out.println("没有存放数据");
    }
    while (cur != null) {
        System.out.print(cur.data + " ");
        cur = cur.next;
    }
   }
 }

第一种方法我们可以用定义三个节点来进行反转,反转完之后可以利用display2进行打印

public Node reverseSingleLinkList() {
    //反转一个单链表,遍历一次
    Node cur = this.head;
    if(cur == null) {
        return null;
    }
    if(cur.next == null) {
        return cur;
    }

    Node prev = null;
    Node newHead = null;

    while(cur != null) {
        Node curNext = cur.next;
        if(cur.next == null) {
            newHead = cur;
        }
        cur.next = prev;
        prev = cur;
        cur = curNext;
    }
    return newHead;
}

第二种方法我们利用头插法进行打印

public Node reverseSingleLinkList2() {
    //利用头插法来反转单链表

    if(this.head == null) {
        return null;
    }
    if(this.head.next == null) {
        return this.head;
    }

    Node node = this.head.next;
    this.head.next = null;
    while (node != null ) {
       addFirst(node.data);
       node = node.next;
    }
    return this.head;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值