单链表
尾插法建立单链表
// 尾插法建立单链表
public LinkList TailBuildList(int[] arr) {
LinkList list = new LinkList();
list.data = 0;
list.next = null;
LinkList r = list;
int count = 0;
while (count < arr.length) {
LinkList p = new LinkList();
p.data = arr[count];
p.next = r.next;
r.next = p;
r = p;
count++;
}
return list;
}
头插法建立单链表
// 头插法建立单链表
public LinkList HeadBuildList(int[] arr) {
LinkList head = new LinkList();
head.data = 0;
head.next = null;
int count = 0;
while (count < arr.length) {
LinkList p = new LinkList();
p.data = arr[count];
p.next = head.next;
head.next = p;
count++;
}
return head;
}
插入
// 在第k个位置插入e
public LinkList insert(LinkList list,int k,int e) {
LinkList p=list.next;
int count=0;
while (count<k) {
p=p.next;
count++;
}
LinkList q=new LinkList();
q.data=e;
q.next=p.next;
p.next=q;
return list;
}
删除
//删除第k个值
public LinkList delete(LinkList list,int k) {
int count=0;
while (count<k) {
list=list.next;
count++;
}
list.next=list.next.next;
return list;
}