Java实现线性表(顺序表,链表)
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现线性表(顺序表,链表)相关的知识,希望对你有一定的参考价值。
顺序表:
package seqTable;
import java.util.ArrayList;
import java.util.Scanner;
public class SeqList {
private int data[];
private int len;
private int maxSize;
public SeqList()
{
data = new int[100];
maxSize = 100;
len = 0;
}
public SeqList(int n)
{
data = new int[n];
maxSize = n;
len = 0;
}
public boolean createList(int n)
{
if (n > maxSize) return false;
Scanner sc = new Scanner(System.in);
for (int i = 0;i<n;i++)
{
data[i] = sc.nextInt();
}
len = n;
return true;
}
public boolean insertList(int n,int e)
{
if (n < 1 || n > len+1) return false;
if (len==maxSize) return false;
for (int i = len-1;i>=n-1;i--)
{
data[i+1] = data[i];
}
data[n-1] = e;
len++;
return true;
}
public boolean deleteList(int n)
{
if (n < 1 || n > len) return false;
if (len==0) return false;
for (int i = n;i<len;i++)
{
data[i-1] = data[i];
}
len--;
return true;
}
public void printList()
{
ArrayList<Integer> arrays = new ArrayList<>();
for (int i = 0;i<len;i++)
{
arrays.add(data[i]);
}
System.out.println(arrays);
}
}
测试类:
package seqTable;
public class TestSeqList {
public static void main(String[] args)
{
SeqList l = new SeqList();
l.createList(5);
l.insertList(1,3);
l.insertList(7,5);
l.deleteList(1);
l.deleteList(6);
l.printList();
}
}
链表:
package LinkList;
import java.util.ArrayList;
import java.util.Scanner;
public class LinkList {
private class Node
{
private int data;
private Node next;
public Node()
{
data = 0;
next = null;
}
public Node(int data)
{
this.data = data;
next = null;
}
}
private Node head;
public LinkList()
{
head = new Node();
}
public boolean createList(int n)
{
Scanner sc = new Scanner(System.in);
Node p = head;
for (int i = 0;i<n;i++) {
Node s = new Node(sc.nextInt());
p.next = s;
p = s;
}
return true;
}
public boolean insertList(int n,int e)
{
int j = 0;
Node p = head;
while(j < n-1 && p!=null)
{
j++;
p = p.next;
}
if (j >= n) return false;
if (p==null) return false;
Node s = new Node(e);
s.next = p.next;
p.next = s;
return true;
}
public boolean deleteList(int n)
{
int j = 0;
Node p = head;
while(j < n-1 && p!=null)
{
j++;
p = p.next;
}
if (j >= n) return false;
if (p==null||p.next==null) return false;
Node q = p.next;
p.next = q.next;
q.next = null;
return true;
}
public int locateElem(int e)//return 链表中出现第一个e 的序号
{
int j = 0;
Node p = head.next;
while(p!=null)
{
j++;
if (p.data == e)
{
return j;
}
p = p.next;
}
return -1;
}
public void printList()
{
ArrayList<Integer> arrays = new ArrayList<>();
Node p = head.next;
while(p!=null)
{
arrays.add(p.data);
p = p.next;
}
System.out.println(arrays);
}
}
测试类:
package LinkList;
public class TestLinkList {
public static void main(String[] args){
LinkList l = new LinkList();
l.createList(5);
l.insertList(6,78);
l.deleteList(78);
System.out.println(l.locateElem(78));
l.printList();
}
}
以上是关于Java实现线性表(顺序表,链表)的主要内容,如果未能解决你的问题,请参考以下文章