数据结构 --链表
单向链表
- 由节点node组成,一个链表拥有不定数量的节点。内存中储存不连续。
- 单向的由** 节点Node 组成,node又包括两个域 数据域data和指针域next**。其中data域是本身数据域,next则是指向下一个节点的地址。
- 有头节点 首节点和尾节点(有些没有头节点),头节点的数据不存放具体的值,指针域指向首节点。
节点类描述
public class Node {
private Object data; //存放结点值
private Node next; //后续节点引用
public Node() {
this(null,null);
}
public Node(Object data) {
this(data,null);
}
public Node(Object data,Node next) {
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
单链表中基本操作实现
- 查找单链表中间节点(快慢指针)
设置两个指针slow和fast,两个指针同时向前走,fast指针每次走两步,slow指针每次走一步,直到fast指针走到最后一个结点时,此时slow指针所指的结点就是中间结点。
public class 链表中间节点 {
public static void main(String[] args){
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
ListNode head = ListNode.arrayToList(array);
ListNode.printList(head);
findMid(head);
}
private static void findMid(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast.next != null){
if(fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
} else {
slow = slow.next;
}
}
System.out.println(slow.val);
}
}
- 按位序号查找get(i)
public Object get(int i) throws Exception { //查(序
Node p = head.getNext();
int j = 0;
while(p != null && j<i) {
p = p.getNext();
++j;
}
return p.getData();
}
- 插入操作insert(int i, Obj x)
public void insert(int i, Object x) throws Exception { //增
Node p = head;
int j = -1;
while(p != null && j < i-1) {
p = p.getNext();
++j;
}
if(j >i-1 || p == null)
throw new Exception("插入位置不合法");
Node s = new Node(x);
s.setNext(p.getNext());
p.setNext(s);
}
- 删除操作
public void remove(int i) throws Exception{ //删
Node p = head;
int j = -1;
while(p.getNext() != null && j < i-1) {
p = p.getNext();
++j;
}
p.setNext(p.getNext().getNext());
}
- 建立操作(头插 尾插)
头插
public void create2(int i) throws Exception {
Node p = head;
int j = 0;
while(p.getNext() != null && j < i-1) {
p = p.getNext();
++j;
}
if(j > i || p.getNext() == null)
throw new Exception("插入位置不合法");
if(i==0)
head.setNext(p.getNext());
else
p.setData(p.getNext());
}
尾插
public void create1(int n) throws Exception {
Scanner sc = new Scanner(System.in);
for(int j=0; j<n; j++)
insert( length() , sc.next());
}
-----未完待续