
*)malloc(sizeof(LNode))
这一句不要,没啥用处,除非你head指向的节点也就是第一个节点的data不需要数据
head->next=NULL这里修改为head=NULL
让head先指向NULL,也就是没有节点
其实这个可以不要,再主函数中,先让链表是空链表即可(即让head=NULL)
head->data=data
head->next=p->next
head->next=p
关键在这里
你仔细考虑一下,一般来说头插法的head只是一个指针,不要对head指向的那个节点 *** 作,对p *** 作完成后,让head指过去即可
所以修改为
p->data=data
//赋值过去,因为你现在申请了p的内存空间
p->next=head
//把head指向的那个节点连接到p的后面,这样完成头插
//
这是head没有用了,p成为链表的头指针
head=p
//head再指向这个链表的头部,也就是p指向的节点,为下一次循环做准备
head=Createlist(head)//链表初始化
主函数中这样不太好,建议不要重名
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= 0i < lengthi ++){
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()
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)