创造自己的节点类
package myNode;
public class Node<T> {
public T data;
public Node next;
public Node() {
this(null,null);
}
public Node(T data) {
this(data,null);
}
public Node(T data,Node next) {
this.data=data;
this.next=next;
}
}
关于链表的方法
package myNode;
import java.util.*;
public class ListFunction<T> {
Node head;
Node newHead;
/*创建节点*/
public ListFunction() {
head=new Node();
newHead=new Node();
}
/*按位查找,输入位置*/
public T get(int n) throws Exception {//按位查找
Node p=head.next;
int j=0;
while(p!=null && j<n) {
p=p.next;
++j;
}
if(p==null || j>n) {
throw new Exception("Wrong");
}
return (T)p.data;
}
/*按值查找,输入想查找的值*/
public void getPosition(T x) throws Exception{//按值查找
Node p=head.next;
int j=0;
while(p!=null && p.data.equals(x)!=true) {
p=p.next;
++j;
}
if(p==null || p.data.equals(x)==false) {
throw new Exception(x+"不存在");
}
System.out.println(x+"存在");
}
/*插入节点*/
public void insert(int i,T x)throws Exception{
Node p=head;
int j=0;
while(p!=null && j<i) {
p=p.next;
++j;
}
Node s=new Node(x);
s.next=p.next;
p.next=s;
}
/*遍历展示节点*/
public void display() {
Node p=head.next;
while(p!=null) {
System.out.print(p.data+" ");
p=p.next;
}
System.out.println();
}
/*删除某个节点*/
public void remove(int i) throws Exception{
Node p=head.next;
int j=0;
while(p.next!=null && j<i-1) {
p=p.next;
++j;
}
if(p.next==null || j>=i) {
throw new Exception("the number you removed is illegal!");
}
p.next=p.next.next;
}
/*返回链表长度*/
public int length() {
Node p=head.next;
int length=0;
while(p!=null) {
p=p.next;
length++;
}
return length;
}
/*倒置链表*/
public void reverse() {
Node cur=head.next;
while(cur!=null) {
head.next=cur.next;
cur.next=newHead.next;
newHead.next=cur;
cur=head.next;
}
head=newHead;
}
/*链表相邻节点两两交换,两个为一组*/
public void changclose() {
Node cur=head;
Node p=head.next;
Node q=head.next.next;
while(p!=null && q!=null) {
cur.next=q;
p.next=q.next;
q.next=p;
cur=p;
p=p.next;
if(p==null) {
break;
}
q=q.next.next.next;
}
}
}