线性链表java实现_java实现线性单链表
/**
*
*?線性單鏈表
*/
public?class?LinkedLinearList?{
private?Node?head;
private?int?length;//?實際長度
/**
*?初始化順序表,長度為length
*/
public?LinkedLinearList()?{
length?=?0;
head?=?new?Node('0',?null);
length++;
}
/**
*?將index位置賦值為c,會覆蓋掉原值
*
*?@param?index
*?@param?c
*/
public?void?set(int?index,?char?c)?{
Node?node?=?head;
int?n?=?0;
while?(n?
if?(node.next?==?null)?{
node.next?=?new?Node('0',?null);
length++;
}
node?=?node.next;
n++;
}
if?(node?==?null)?{
node?=?new?Node(c,?null);
length++;
}?else?{
node.data?=?c;
}
}
/**
*?取得下標為index的值,如果為空返回ascii為零的字符
*
*?@param?index
*?@param?c
*?@return
*/
public?char?get(int?index)?{
if?(index?>?length?-?1?||?index?
System.out.println("out?of?size?exception!");
return?0;
}?else?{
Node?node?=?head;
int?n?=?0;
while?(n?
node?=?node.next;
n++;
}
return?node.data;
}
}
/**
*?在index位置插入c,不會覆蓋掉原值
*
*?@param?index
*?@param?c
*/
public?void?insert(int?index,?char?c)?{
if?(index?
System.out.println("out?of?size?exception!");
return;
}?else?{
Node?node?=?head;
int?n?=?0;
while?(n?
if?(node.next?==?null)?{
node.next?=?new?Node('0',?null);
length++;
}?else?{
node?=?node.next;
}
n++;
}
if?(node.next?==?null)?{
node.next?=?new?Node(c,?null);
}?else?{
Node?newNode?=?new?Node(c,?null);
newNode.next?=?node.next;
node.next?=?newNode;
}
length++;
}
}
/**
*?返回長度
*
*?@return
*/
public?int?length()?{
return?length;
}
/**
*?刪除下標為index的元素
*
*?@param?index
*/
public?void?delete(int?index)?{
if?(index?>?length?-?1?||?index?
System.out.println("delete?not?exist?element?exception");
}?else?{
Node?node?=?head;
int?n?=?0;
while?(n?
if?(node.next?==?null)?{
node.next?=?new?Node('0',?null);
length++;
}?else?{
node?=?node.next;
}
n++;
}
node.next?=?node.next.next;
length--;
}
}
/**
*?查找c元素,返回第一個找的c元素的下標,沒有找到返回-1
*
*?@param?c
*/
public?int?findChar(char?c)?{
Node?node?=?head;
int?n?=?0;
while?(n?
if?(node.data?==?c)
return?n;
node?=?node.next;
n++;
}
return?-1;
}
public?void?show()?{
Node?node?=?head;
int?n?=?0;
while?(n?
System.out.print(node.data?+?",");
node?=?node.next;
n++;
}
System.out.println();
}
public?static?void?main(String[]?args)?{
LinkedLinearList?lll?=?new?LinkedLinearList();
lll.set(0,?'a');
lll.set(1,?'b');
lll.set(2,?'c');
lll.set(3,?'d');
lll.set(4,?'e');
lll.show();
lll.insert(2,?'f');
lll.show();
lll.delete(2);
lll.show();
System.out.println(lll.length());
System.out.println(lll.findChar('c'));
lll.set(0,?'z');
lll.show();
}
class?Node?{
char?data;
Node?next;
public?Node(char?data,?Node?next)?{
this.data?=?data;
this.next?=?next;
}
}
}
總結
以上是生活随笔為你收集整理的线性链表java实现_java实现线性单链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STM32——串口通信
- 下一篇: python制作fnt字体打包工具