62,614
社区成员
发帖
与我相关
我的任务
分享
package com.wwy.thirdTest;
/**
* 交换整个链表中相邻的两个整链(不是数据),分别做单链表与双链表的,不考虑循环链表
* @author wWX161568
*
*/
public class Test3_2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Node1 n1 = new Node1("111");
Node1 n2 = new Node1("222");
Node1 n3 = new Node1("333");
Node1 n4 = new Node1("444");
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = null;
//1-->2-->3-->4
System.out.println("n2 --> n3" + n2.next.data);
//互换后的链表结构1-->3--2--4
exchangeSingle(n2,n3);
System.out.println("n3 --> n2" + n1.next.data);
}
/**
* 单链表节点类
* @author wWX161568
*
*/
private static class Node1
{
String data;
Node1 next;
public Node1(String str)
{
data = str;
}
}
/**
* 单链表相邻两个节点互换
* @param previous
* @param next
*/
public static void exchangeSingle(Node1 previous,Node1 next)
{
if(previous.next != next)
{
System.out.println("不是两个相邻的节点,请检查!!!");
}
else
{
//把前一个节点指向后一个节点的下一个节点
previous.next = next.next;
//在吧后一个节点的下一个节点指向前一个节点
next.next = previous;
}
}
}
private static class Node1
{
String data;
Node1 previous;
Node1 next;
public Node1(String str)
{
data = str;
}
}