import cj.util.*;
class Link<E> {
public E data;
public Link<E> next;
public Link(E data) {
this.data = data;
}
}
class LinkList<E> {
public Link<E> head;
public int num;
public LinkList() {
head = null;
num = 0;
}
public boolean isEmpty() {
return num == 0;
}
public void display() {
Link<E> cur = head;
while (cur != null) {
P.prn(cur.data + " ");
cur = cur.next;
}
P.prnEnter();
}
// construct head
public void insertHead(E value) {
Link<E> link = new Link<E>(value);
link.next = head;
head = link;
num++;
}
// delete head
public Link<E> deleteHead() {
Link<E> temp = head;
head = head.next;
num--;
return temp;
}
// get the Node through index
public Link<E> get(int index) {
if(index > this.getNum() || index < 0) {
try {
throw new IndexOutOfBoundsException();
}catch (Exception e) {
e.printStackTrace();
}
}
Link<E> cur = head;
for (int i = 0; i < getNum(); i++) {
if (i == index)
return cur;
else
cur = cur.next;
}
return null;
}
public Link<E> get(E data) {
if(data == null)
try {
throw new Exception("data is null");
} catch (Exception e) {
e.printStackTrace();
}
Link<E> cur = head;
while(cur != null) {
if(cur.data.equals(data))
return cur;
else
cur = cur.next;
}
return null;
}
// remove a Node
public void remove(int index) {
if(index > this.getNum() || index < 0) {
try {
throw new IndexOutOfBoundsException();
}catch (Exception e) {
e.printStackTrace();
}
}
else if(index == 0) {
this.deleteHead();
}
else if(index == this.getNum()) {
this.get(index - 1).next = null;
}
else {
this.get(index - 1).next = this.get(index + 1);
}
}
public LinkList<E> reverse() {
LinkList<E> temp = new LinkList<E>();
Link<E> cur = head;
for(int i=0; i<this.getNum() && cur != null; i++, cur = cur.next) {
temp.insertHead(cur.data);
}
return temp;
}
public Link<E> getHead() {
return head;
}
public void setHead(Link<E> head) {
this.head = head;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
public class SingleLink {
/**
* @param args
*/
public static void main(String[] args) {
LinkList<Long> sl = new LinkList<Long>();
for(int i = 0; i < 10; i++) {
Long value = (long)(Math.random() * 100);
sl.insertHead(value);
}
sl.display();
LinkList<Long> temp = new LinkList<Long>();
temp = sl.reverse();
// while(!sl.isEmpty()) {
// sl.deleteHead();
// sl.display();
// }
P.prn("done");
temp.remove(2);
temp.display();
}
}
打印工具包
package cj.util;
public class P {
public static void pr(Object s)
{
System.out.print(s);
}
public static void prn(Object a)
{
System.out.println(a);
}
public static void prnEnter()
{
P.prn(" ");
}
}注意这里序号是从1开始的, remove方法有点别扭.
reverse方法即反转了原链表, 又能生成一份拷贝. 如果是链表顺序不变, 则和clone方法一样
自己实现一遍,可以知道如果有个尾指针, 查找和删除时都会方便很多,而且效率会提高,
因为要是想插到最后的位置去, 不必再从头的next指针一个一个去找了.

481

被折叠的 条评论
为什么被折叠?



