public class singleLinkedList<T> {
/**
* 结点类
*/
private static class Node<T>
{
T nodeValue;//数据域
Node<T> nextNode;//指针域
Node(T nodeValue,Node<T> nextNode){
this.nodeValue=nodeValue;
this.nextNode=nextNode;
}
Node(T nodeValue){
this(nodeValue, null);
}
}
//下面是singleLinkedList 类的数据成员和方法
private Node<T> head,tail;
public singleLinkedList() {
head=tail=null;
}
public boolean isEmpty() {
return head==null;
}
//添加头结点
public void addToHead(T iteam) {
head=new Node<T>(iteam);
if(tail==null)tail=head;
}
//添加尾指针
public void addToTail(T item) {
if(!isEmpty()){
tail.nextNode=new Node<T>(item);
tail=tail.nextNode;
}
else {
head=tail=new Node<T>(item);
}
}
private void printList() {
if(isEmpty()){
System.out.println("null");
}
else {
for(Node<T> pNode=head;pNode!=null;pNode=pNode.nextNode){
System.out.println(pNode.nodeValue);
}
}
}
//表头插入结点
private void addFirst(T item) {
Node<T> newNode=new Node<T>(item);
newNode.nextNode=head;
head=newNode;
}
//表尾插入结点
private void addLast(T item) {
Node<T> newNode=new Node<T>(item);
tail.nextNode=newNode;
tail=newNode;
}
//表头删除结点
private void removeFirst () {
if(!isEmpty()){
head=head.nextNode;
}
else {
System.out.println("the list is null now");
}
}
//表尾删除结点,效率低,全部遍历
public void removeLast() {
Node<T> prevNode=null,currNode=head;
while(currNode.nextNode!=null){
prevNode=currNode;
currNode=currNode.nextNode;
if(currNode.nextNode==null)prevNode.nextNode=null;
}
}
//遍历方便,可以hasnext函数
private boolean insert(T appointedItem,T item) {
Node<T> prevNode=head,currNode=head.nextNode,newNode;
newNode=new Node<T>(item);
if(!isEmpty()){
while ((currNode!=null)&&(!appointedItem.equals(currNode.nodeValue))) {
prevNode=currNode;
currNode=currNode.nextNode;
}
newNode.nextNode=currNode;
prevNode.nextNode=newNode;
return true;
}
return false;
}
//删除中间结点
private void remove(T item) {
Node<T> currNode=head,prevNode=null;
boolean found=false;
while(currNode!=null&&!found){
if(item.equals(currNode.nodeValue)){
if(prevNode==null)removeFirst();
else prevNode.nextNode=currNode.nextNode;
found=true;
}
else {
prevNode=currNode;
currNode=currNode.nextNode;
}
}
}
public static void main(String[] args) {
singleLinkedList<Integer> ls=new singleLinkedList<Integer>();
ls.addToHead(1);
ls.addLast(2);
ls.addLast(4);
ls.insert(4, 3);
ls.printList();
}
}
数据结构—单链表
最新推荐文章于 2024-09-25 20:49:26 发布