线性表
#学习目标
- 掌握线性表基础思想、优缺点、常见分类,能复述;
- 能使用
java 代码实现线性表创建,元素插入、删除、元素修改、查找; - 完成一道相关题目。
#基础思想、优缺点
1.基础思想
在内存中可以非连续存储,提高空间利用率,理论上其大小是内容能使用空间的大小(非连续);
2.优缺点
优点:
缺点:
查找速度很慢。
#常见分类
**单向链表:**一个节点只指向下一个节点
**双向链表:**一个节点同时包含下一个节点和上一个节点的引用(指针)
**环形链表:**链表首位相连(单、双链表均可),从任何一个节点可以遍历整个链表
#实现
1.节点:包含下一个节点域、数据域
public class SingleNode {
int data;
SingleNode next;
public SingleNode(){}
public SingleNode(int data){
this.data = data;
}
public SingleNode(int data,SingleNode next){
this.data = data;
this.last = next;
}
}
package com.piziwang.linkedlist;
public class MyLinkedList{
SingleNode first;
SingleNode last;
int size;
}
后面方法均是MylinkedList 方法
2.插入节点
public void add(int value){
SingleNode l = last;
SingleNode newNode = new SingleNode(value);
last = newNode;
if(l == null){
first = newNode;
}else {
l.netx = newNode;
}
size++;
}
3.遍历
public void print(){
SingleNode node = first;
while (node != null) {
System.out.print(node.data);
node = node.next;
if (node != null) {
System.out.print("-->");
}
}
System.out.println();
}
需要改MylinedList 类,实现Iterable 接口
for(Object o : list){
System.out.println(o);
}
package com.piziwang.linkedlist;
public class MyLinkedList implements Iterable{
SingleNode first;
SingleNode next;
int size;
@Override
public Iterator iterator() {
return new Iterator() {
SingleNode node = first;
@Override
public boolean hasNext() {
return node != null;
}
@Override
public Object next() {
int value = node.data;
node = node.next;
return value;
}
};
}
}
4.查找
public int getIndex(int value){
SingleNode current = first;
int index = 0;
while (index<size) {
if (current.data == value) {
return index;
}
current = current.next;
index ++;
}
return -1;
}
public int getValue(int index){
checkElementIndex(index);
return node(index).data;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index)) {
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
SingleNode node(int index) {
SingleNode x = first;
for (int i = 0; i < index; i++) {
x = x.next;
}
return x;
}
5.清空
public void clear(){
for (SingleNode x = first; x != null; ) {
SingleNode next = x.next;
x.setData(0);
x.next=null;
x = next;
}
first = last = null;
size = 0;
}
6.求长度
public int size() {
return size;
}
7.删除节点
public boolean remove(int value){
for(SingleNode x = first;x != null; x = x.next){
if (x.data == value) {
x.data=x.next.data;
x.next=x.next.next;
}
}
return false;
}
8.去重
|