如果您发现代码有任何问题,请及时留言,或者QQ498442999与我讨论,期待与您一起进步~
定义一个头结点保存表的行数和列数
且以一行数据为一个结点,如下图
import java.util.Scanner;
class TableLinkList
{
Scanner in = new Scanner(System.in);
// 结点类
class Node
{
int[] data = new int[10];
Node next;
}
// 头结点类
class HNode
{
int Row; // 表行数
int Column; // 表列数
Node next;
public HNode()
{
}
public HNode(int r, int c)
{
this.Row = r;
this.Column = c;
}
}
HNode head; // 头结点
Node r; // 尾结点
public TableLinkList()
{
head = new HNode();
r = new Node();
}
public void CreateTable()
{
System.out.print("请输入表的行数,列数:");
head.Row = in.nextInt();
head.Column = in.nextInt();
for (int i = 0; i < head.Row; i++)
{
System.out.print("第" + (i + 1) + "行,请输入" + head.Column + "个元素:");
Node n = new Node();
for (int j = 0; j < head.Column; j++)
n.data[j] = in.nextInt();
if (head.next == null)
head.next = n;
else
r.next = n;
r = n;
}
}
public void DispTable()
{
Node current = head.next;
while (current != null)
{
for (int i = 0; i < head.Column; i++)
System.out.print(current.data[i] + " ");
System.out.println();
current = current.next;
}
}
public TableLinkList LinkTable(TableLinkList t2, int t1C, int t2C)
{
t1C -= 1; // 数组下标从0开始
t2C -= 1;
TableLinkList t3 = new TableLinkList();
t3.head.Row = 0;
t3.head.Column = head.Column + t2.head.Column;
Node n1 = new Node();
Node n2 = new Node();
Node n3;
n1 = head.next;
while (n1 != null)
{
n2 = t2.head.next;
while (n2 != null)
{
if (n1.data[t1C] == n2.data[t2C])
{
n3 = new Node();
for (int i = 0; i < head.Column; i++)
n3.data[i] = n1.data[i];
for (int j = 0; j < t2.head.Column; j++)
n3.data[head.Column + j] = n2.data[j];
if (t3.head.next == null)
t3.head.next = n3;
else
t3.r.next = n3;
t3.r = n3;
t3.head.Row++;
}
n2 = n2.next;
}
n1 = n1.next;
}
return t3;
}
}
public class NaturalConnection
{
public static void main(String args[])
{
TableLinkList t1 = new TableLinkList();
t1.CreateTable();
TableLinkList t2 = new TableLinkList();
t2.CreateTable();
TableLinkList t3 = new TableLinkList();
t3 = t1.LinkTable(t2, 3, 1);
System.out.println("A");
t1.DispTable();
System.out.println("B");
t2.DispTable();
System.out.println("C=link(A3,B1)");
t3.DispTable();
}
}
输出:
请输入表的行数,列数:3 3
第1行,请输入3个元素:1 2 3
第2行,请输入3个元素:2 3 3
第3行,请输入3个元素:1 1 1
请输入表的行数,列数:3 2
第1行,请输入2个元素:3 5
第2行,请输入2个元素:1 6
第3行,请输入2个元素:3 4
A
1 2 3
2 3 3
1 1 1
B
3 5
1 6
3 4
C=link(A3,B1)
1 2 3 3 5
1 2 3 3 4
2 3 3 3 5
2 3 3 3 4
1 1 1 1 6