单链表的反转

单链表的反转


import java.util.ArrayList;
import java.util.Stack;

public class LinkList2 {

	public Node head;
	public Node current;

	public static void main(String[] args) {
		LinkList2 list = new LinkList2();//新建一个单链表
		// 向LinkList2 中添加数据
		for (int i = 0; i < 10; i++) {
			list.add(i);// 向链表中添加数据
		}
			
		Node node = reverseList(list.head);
		list.print(node);// 从head节点开始遍历输出
	}

	//方法:链表的反转
    public static Node reverseList(Node head) {

        //如果链表为空或者只有一个节点,无需反转,直接返回原链表的头结点
        if (head == null || head.next == null) {
            return head;
        }

        Node current = head;
        Node next = null; //定义当前结点的下一个结点
        Node reverseHead = null;  //反转后新链表的表头

        while (current != null) {
            next = current.next;  //暂时保存住当前结点的下一个结点,因为下一次要用

            current.next = reverseHead; //将current的下一个结点指向新链表的头结点
            reverseHead = current;  

            current = next;   // 操作结束后,current节点后移
        }

        return reverseHead;
    }
    
	// 方法:向链表中添加数据
	public void add(int data) {
		// 判断链表为空的时候
		if (head == null) {// 如果头结点为空,说明这个链表还没有创建,那就把新的结点赋给头结点
			head = new Node(data);
			current = head;
		} else {
			// 创建新的结点,放在当前节点的后面(把新的结点和链表进行关联)
			current.next = new Node(data);
			// 把链表的当前索引向后移动一位
			current = current.next; // 此步操作完成之后,current结点指向新添加的那个结点
		}
	}
	// 方法:遍历链表(打印输出链表。方法的参数表示从节点node开始进行遍历
	public void print(Node node) {
		if (node == null) {
			return;
		}

		current = node;
		while (current != null) {
			System.out.println(current.data);
			current = current.next;
		}
	}
	// 节点类
	class Node {
		// 注:此处的两个成员变量权限不能为private,因为private的权限是仅对本类访问。
		int data; // 数据域
		Node next;// 指针域

		public Node(int data) {
			this.data = data;
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值