示例1:
输入:1 --> 2 --> 3
输出: 2
示例2:
输入:1 --> 2 --> 3 --> 4
输出:2
思路:
如果是数组,我们可以怎么求中间元素:arr[(arr.length-1/2]
相类比,如果是链表
a.求链表的长度
b.从头开始遍历链表,并计数
public class MiddleElement{
public static int middleElement(Node head){
//求链表长度
int length = 0;
Node x =head;
while(x != null){
length++;
x = x.next;
}
//计算中间元素的索引
int index = (length -1 )/2;
//从头开始遍历链表,并计数
int i = 0;
x = head;
while(x < index){
x = x.next;
i++;
}
return x.value;
}
public static void main(String []args){
Node head = new Node(4);//使用头插法建立链表
head = new Node(3,head);
head = new Node(2,head);
head = new Node(1,head);
system.out.println(middleElement(head));
}
}
public calss Node{
int value;
Node next;
public Node(int value){
this.value = value;
}
public Node(int value,Node next){
this.value = value;
this.next = next;
}
}