单链表的反转-Java实现

本文介绍了一种简单的链表数据结构,并提供了链表的基本操作,包括插入元素和反转链表的功能。通过Java代码实现了单链表节点的定义、元素的插入及链表的反转过程,并演示了如何打印链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

public class LinkedList {
	private Node root;
	public void insert(int data){
		Node cur = root;
		if(root==null){
			root = new Node(data);
			return;
		}
		while(cur.next!=null){
			cur = cur.next;
		}
		cur.next = new Node(data);
	}
	public Node invertedList(){
		Node cur = null;
		Node pre = null;
		Node next = null;
		if(root == null){
			return null;
		}
		cur = root;
		while(cur!=null){
			next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}
		root=pre;
		return root;
	}
	public void print(){
		Node cur = root;
		if(root == null){
			return;
		}
		while(cur!=null){
			System.out.print(cur.data+" ");
			cur = cur.next;
		}
	}
	
	public static void main(String[] args){
		LinkedList list = new LinkedList();
		list.insert(1);
		list.insert(2);
		list.insert(3);
		list.insert(4);
		list.print();		
		System.out.println();
		list.invertedList();
		list.print();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值