现在的位置: 首页 > 综合 > 正文

用java实现单向链表

2018年03月29日 ⁄ 综合 ⁄ 共 1514字 ⁄ 字号 评论关闭
主要就是简单的指针移动,之前有人让我帮改了一个链表的程序,但我觉得实现有问题 改完 自己又写了一个,代码在下面

public class MyLinkedList {
    int
size;
    Node

head;
    Node
tail;

    public
MyLinkedList() {
   
    size =
0;
   
    head =
null;
   
    tail =
null;
    }

    public void
addElement(A inNode) {
   
    if (head ==
null) {
   
   
    head = tail
= new Node
(inNode);
   
    } else
{
   
   
    tail.next =
new Node(inNode);
   
   
    tail =
tail.next;
   
    }
   
   
size++;
    }

    public void
updateElement(int index, A content) {
   
    if (index
< 0 || index >= size) {
   
   
   
return;
   
    }
   
    Node

curNode = head;
   
    while (index
> 0) {
   
   
    curNode =
curNode.next;
   
   
   
index--;
   
    }
   
   
curNode.content = content;
    }

    public A
getElement(int index) {
   
    if (index
< 0 || index >= size) {
   
   
    return
null;
   
    }
   
    Node
curNode = head;
   
    while (index
> 0) {
   
   
    curNode =
curNode.next;
   
   
   
index--;
   
    }
   
    return
curNode.content;
    }

    public void
deleteElement(int index) {
   
    if (index
< 0 || index >= size) {
   
   
   
return;
   
    }
   
    if (index ==
0) {
   
   
    head =
head.next;
   
   
    if (size ==
1) {
   
   
   
    tail =
null;
   
   
    }
   
   
   
size--;
   
   
   
return;
   
    }
   
    Node

preNode = null;
   
    Node
curNode = head;
   
    while (index
> 0) {
   
   
    preNode =
curNode;
   
   
    curNode =
curNode.next;
   
   
   
index--;
   
    }

   
    preNode.next
= curNode.next;
   
    if (index ==
(size - 1)) {
   
   
    tail =
preNode;
   
    }
   
   
size--;
    }

    public void
deleteElement(A deleNode) {
   
    //
这里可以用来报异常
   
    if (size ==
0) {
   
   
   
return;
   
    }

   
    if
(head.content.equals(deleNode)) {
   
   
    head =
head.next;
   
   
    if (size ==
1) {
   
   
   
    tail =
null;
   
   
    }
   

抱歉!评论已关闭.