java实现单链表逆转

本文介绍了一种链表数据结构,并实现了一个简单的链表反转算法。该算法接收一个链表头结点和需要反转的节点数量作为参数,通过迭代方式完成指定数量节点的反转操作。文章还提供了一个完整的Java程序示例,包括链表节点定义、链表创建及反转后的输出。

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

import java.text.DecimalFormat;
import java.util.Scanner;
class Node{
	int address;
	int data;
	int nextAddress;
	Node next;
	
	public Node(){
		
	}
	
	public Node(Node next){
		this.next = next;
	}
	
	public Node(int address,int data,int nextAddress){
		this.address = address;
		this.data = data;
		this.nextAddress = nextAddress;
	}
}
public class Main{
	private static Node[] nodes = new Node[100005];
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int headAddress = scan.nextInt();
		int N = scan.nextInt();
		int K = scan.nextInt();//反转的节点数
		for(int i=0;i<N;i++){
			int address = scan.nextInt();
			int data = scan.nextInt();
			int nextAddress = scan.nextInt();
			nodes[address] = new Node(address,data,nextAddress);
		}
		
		Node head = createLink(headAddress);
		Node newHead = resver(head,K);
		System.out.println("-----------------------------------");
		DecimalFormat df = new DecimalFormat("00000");
		while(newHead!=null){
			System.out.println(df.format(newHead.address)+" "+newHead.data+" "+(newHead.nextAddress==-1?-1:df.format(newHead.nextAddress)));
			newHead = newHead.next;
		}
	}
	
	public static Node resver(Node head,int K){
		Node newNode,oldNode,temp;
		newNode = head.next;
		oldNode = newNode.next;
		int cnt = 1;
		int tmp;
		while(cnt<K){
				temp = oldNode.next;
				oldNode.next = newNode;
				oldNode.nextAddress = newNode.address;
				newNode = oldNode;
				oldNode = temp;
				cnt++;
			}
		head.next.next = oldNode;
		head.next.nextAddress = -1;
		return newNode;
	}
	
	public static Node createLink(int headAddress){
		Node head = new Node();
		Node finalHead = head;
		int address = headAddress;
		int data,nextAddress;
		while(address!=-1){
			head.next = nodes[address];
			address = nodes[address].nextAddress;
			head = head.next;
		}
		return finalHead;
	}
}
00100 6 6
00000 4 99999
00100 1 12309
68237 6 -1
33218 3 00000
99999 5 68237
12309 2 33218
-----------------------------------
68237 6 99999
99999 5 00000
00000 4 33218
33218 3 12309
12309 2 00100
00100 1 -1


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值