本文目錄一覽:
- 1、什麼是頭指針?頭指針跟頭結點有什麼區別和聯繫?
- 2、數據結構java,頭插法建立單鏈表,h為頭結點,那p是結點還是指針?是結點的話怎麼p.data?
- 3、用JAVA編寫鏈表類,要求編寫能夠從頭部添加節點。
什麼是頭指針?頭指針跟頭結點有什麼區別和聯繫?
在線性表的鏈式存儲結構中,頭指針指鏈表的指針,若鏈表有頭結點則是鏈表的頭結點的指針,頭指針具有標識作用,故常用頭指針冠以鏈表的名字。頭結點是為了操作的統一、方便而設立的,放在第一元素結點之前,其數據域一般無意義(當然有些情況下也可存放鏈表的長度、用做監視哨等等),有頭結點後,對在第一元素結點前插入結點和刪除第一結點,其操作與對其它結點的操作統一了。而且無論鏈表是否為空,頭指針均不為空。首元結點也就是第一元素結點,它是頭結點後邊的第一個結點。
數據結構java,頭插法建立單鏈表,h為頭結點,那p是結點還是指針?是結點的話怎麼p.data?
一個節點分為兩個部分,一部分是自身的數據域,一部分是指向下一個節點的指針域。你想複雜了
public class Node {
public int data; //數據域
public Node next; //指針域,指向下一個節點
public Node(int data){
this.data=data;
}
}
用JAVA編寫鏈表類,要求編寫能夠從頭部添加節點。
public class ZLinkedList {
private int size;
private Node head;
public ZLinkedList(){
size = 0;
}
public void headInsert(Object obj){
//if(null== obj) {// do something}
Node temp = new Node(obj);
if(size ==0){
head = temp;
}else{
temp.setNext(head);
head = temp;
}
size++;
}
public void preOrder(){
int length = size;
Node temp = head;
for(int i= 0;i length;i ++){
System.out.println(temp.getValue());
temp = temp.getNext();
}
}
private static class Node{
private Object value;
private Node next;
Node(){
}
Node(Object val){
this.value = val;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public static void main(String[] args) {
ZLinkedList test = new ZLinkedList();
test.headInsert(“1”);
test.headInsert(“2”);
test.headInsert(“3”);
test.preOrder();
}
}
原創文章,作者:YOPP8,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/130185.html