您的位置:首页 > 编程语言 > Java开发

Java实现查找链表的中间节点,(在未知链表长度的情况下)

2017-05-17 22:50 393 查看
下面是自己实现的一个类似于LinkedList类,其中getMidNode方法是获取链表的中间节点的实现方法(在未知列表长度的情况下),大致思路如下:

1、首先在方法中定义temp 、 temp2两个局部变量。

2、temp每次循环next一次,temp2每次循环next两次,当temp2.next==null时表示temp2已经执行到达了链表的末尾,而temp刚好执行到链表的一半。

备注:此种做发的思路类似于C语言的指针操作,设立两个指针,一个单步走,一个两步走,当大步指针到达链表尾部的时候,小步指针也正好位于链表中间位置。由于本人能力有限,工作之余写一些东西分享给各位,希望对大家有所帮助,如有写得不好的地方希望各位给我留言,我并及时纠正。如你阅读之后觉得对你有所帮助,千万不要忘记鼓励一下我,麻烦顶一下哦!!!废话不多说,直接上完整源代码。

package lsp.connection;

/**
* 自己实现类似于JDK的LinkedList类
*
* @author Administrator
*
* @param <E>
*/
public class LspLinkedList<E> {

private Node<E> first;
private Node<E> last;
private int size;

public int size(){
return size;
}

/**
* 添加一个节点
* @param e
*/
public void add(E e){

Node<E> node = new Node<E>();
if(first == null){
node.previous = null;
node.item = e;
node.next = null;
first = node;
last = node;//首尾节点为同一个
}else {
//直接向last中插入下一节点
node.previous = last;
node.item = e;
node.next = null;
//给last的下一节点赋值为当前传入的节点值
last.next = node;

//重新给last节点赋值
last = node;
}
size++;
}

/**
* 根据index获取节点
* @param index
* @return
*/
public E get(int index){
if(first != null){
Node<E> temp = first;
for (int i = 0; i < index; i++) {
temp = temp.next;
}
return temp.item;
}
return null;
}

/**
* 根据index删除节点元素
* @param index
*/
public void remove(int index){
if(first != null){
Node<E> temp = first;
for (int i = 0; i < index; i++) {
temp = temp.next;
}

Node<E> before = temp.previous;
Node<E> after = temp.next;
before.next = after;
after.previous = before;

size--;
}
}

/**
* 获取链表的中间节点(在未知链表长度的情况下)
* @return
*/
public E getMidNode(){
if(first != null){
Node<E> temp = first;
Node<E> temp2 = temp.next;
while(temp.next != null && temp2.next != null){
temp = temp.next;
temp2 = temp2.next;
if(temp2.next != null){
temp2 = temp2.next;
}
}
return temp.item;
}
return null;
}

public static void main(String[] args) {
LspLinkedList<String> lspLinkedList = new LspLinkedList<String>();
lspLinkedList.add("111");
lspLinkedList.add("222");
lspLinkedList.add("333");
lspLinkedList.add("444");
lspLinkedList.add("555");
System.out.println(lspLinkedList.getMidNode());
}

}
package lsp.connection;
/**
* 节点类
* @author Administrator
*
* @param <E>
*/
public class Node<E> {

Node<E> previous;
E item;
Node<E> next;

public Node() {
}

public Node(E item, Node<E> previous, Node<E> next) {
super();
this.item = item;
this.previous = previous;
this.next = next;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 链表 linkedlist
相关文章推荐