package com.qbsea.arithmetic.linked;
public class LinkedListTest {
public static void main(String[] args) {
//往链表里增加五个数
LinkedList linkedList =new LinkedList();
Node node1 = new Node();
node1.setData("1");
linkedList.add(node1);
//
Node node2 = new Node();
node2.setData("2");
linkedList.add(node2);
//
Node node3 = new Node();
node3.setData("3");
linkedList.add(node3);
//
Node node4 = new Node();
node4.setData("4");
linkedList.add(node4);
//
Node node5 = new Node();
node5.setData("5");
linkedList.add(node5);
//开始找中间元素
Node currentNode = linkedList.getHead();
Node middleNode = linkedList.getHead();
int i=1;
while(currentNode.getNext()!=null) {
if(i%2==0) {
middleNode = middleNode.getNext();
}
currentNode = currentNode.getNext();
i++;
}
System.out.println("the middleNode is "+middleNode.getData());
}
public static class LinkedList{
private Node head;//头指针
private Node tail;//尾指针
public void add(Node node) {
if(head==null) {
head = node;
tail=node;
return ;
}
tail.next=node;
tail=node;
}
// LinkedList的set and get method
public Node getHead() {
return head;
}
public void setHead(Node head) {
this.head = head;
}
public Node getTail() {
return tail;
}
public void setTail(Node tail) {
this.tail = tail;
}
}
public static class Node {
private Node next;// 指针
private String data;
// set and get method
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
}
LinkedListTest
最新推荐文章于 2022-03-26 20:42:47 发布