让我们以这个标记为例
<div id="my_div" custom="some custom value">
<div id="sec_div" data-custom="other custom value">
<script>
console.log(document.getElementById("my_div").getAttribute("custom"))// outputs "some custom value"
console.log(document.getElementById("sec_div").dataset.custom)// outputs "other custom value"
</script>
在您的do-while循环中,您的条件是到目前为止的要素之一:
do
{
cout<<temp->data;
temp=temp->link; // (1) temp is now pointing to the next element
}
while(temp->link!=NULL); // (2) check if temp has a next element
在(1),您假定存在下一个元素(只要您不取消引用指针就可以),然后在条件(2)中,检查该下一个元素是否具有下一个元素。相反,您应该检查(1)中设置的指针是否有效。即:
do {
temp = temp->link;
while(temp != NULL);
或使用while循环来正确处理传递给方法的空指针(并且不需要临时指针:]
void printList(node * a) {
while (a) {
cout<<a->data;
a = a->link;
}
}
#include <iostream>
using namespace std;
struct node
{
int data;
node * link;
};
node * createList(int a)
{
node * temp =new node();
temp->data=a;
temp->link=NULL;
node * A=new node();
A=temp; // you lose the pointer hold in A this is a memory leak
return A;
}
void printList(node * a)
{
node * temp=NULL;
temp=a;
do
{
cout<<temp->data;
temp=temp->link; // on the last loop temp will be null
}
while(temp->link!=NULL); // you access temp->link so on the last loop when temp is null you are dereferencing null, it undefined behavior
}
int main()
{
node * A=createList(3);
printList(A);
cout<<4;
//don't forget to delete what you new
return 0;
}