标签:list let 指定 equals 链表 oid class search rgs
/**
* @description 线性表的链式表示和实现
* @author wcc
*/
public class MyLinkedList<T> {
private Node<T> head;
private int length;
public MyLinkedList(){
length = 0;
head = new Node<>(null);
}
//在指定位置处添加结点
public void add(T obj,int position){
if (position<1||position>(length+1)){
System.out.println("添加结点位置错误");
System.exit(1);
}
Node<T> p = head;
Node<T> q = p.next;
for (int i = 0; i < position-1; i++) {
p = q;
q = q.next;
}
p.next = new Node<>(obj,q);
length++;
}
//删除指定为位置的结点,并返回删除的结点对象数据,position为1,删除第一个结点
public T delete(int position){
if (position<1||position>length){
System.out.println("结点元素不存在");
System.exit(1);
}
Node<T> p = head;
Node<T> q = head.next;
for (int i = 0; i < position-1; i++) {
p = q;
q = q.next;
}
p.next = q.next;
length--;
return q.data;
}
//查找某个位置的结点数据
public T find(int position){
if (position<1||position>length){
System.out.println("结点元素不存在");
return null;
}
Node<T> p = head;
for (int i = 0; i < position; i++) {
p = p.next;
}
return p.data;
}
//查找某个数据在链表中的位置,如不存在返回-1
public int searchNodeData(T data){
Node<T> p = head;
int position = 1;
while (p.next!=null){
p = p.next;
if (p.data.equals(data)){
return position;
}
position++;
}
return -1;
}
public void nextOrder(){
Node<T> p =head.next;
while(p!=null){
System.out.println(p.data);
p=p.next;
}
}
public static void main(String[] args) {
MyLinkedList<Integer> linkedList = new MyLinkedList<>();
linkedList.add(1,1);
linkedList.add(2,1);
linkedList.add(3,2);
linkedList.add(4,1);
linkedList.nextOrder();
Integer delete = linkedList.delete(3);
System.out.println("delete = " + delete);
linkedList.nextOrder();
Integer integer = linkedList.find(3);
System.out.println("integer = " + integer);
int nodeData = linkedList.searchNodeData(2);
System.out.println("nodeData position " + nodeData);
}
}
class Node<T> {
T data;
Node<T> next;
public Node(Node<T> node) {
next = node;
}
public Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
标签:list let 指定 equals 链表 oid class search rgs
原文地址:https://www.cnblogs.com/lovelywcc/p/14155231.html