参考资料 LinkedListBasics.pdf
一、遍历
当遍历一个链表时,测试条件为current!=NULL,移动步骤为current=current->next 。
int Length(struct node* head)
{
printf("---- iterate list ----\n");
int count = 0;
struct node* current = head;
while(current != NULL)
{
printf("data =%d ;\n",current->data);
count ++;
current = current->next;
}
return count;
}
二、从Head后插入
最简单的方法是在头节点的末尾插入节点,但是它的插入顺序跟它的排列顺序刚好相反。呵呵,如果你不介意的话,这个不失为一种简单易行的方法。
void Push(struct node** headRef, int data){
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef;
*headRef = newNode;
}
struct node* AddAtHead() {
struct node* head = NULL;
int i;
for (i=1; i<6; i++) {
Push(&head, i);
}
// head == {5, 4, 3, 2, 1};
return(head);
}
三、从链表末尾插入
先要找到末尾的节点~
void PushTail(struct node** headRef, int data){
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
//special case for lenght 0
if(tail == NULL)
{
printf("tail == NULL");
*headRef = newNode;
}
else
{
struct node* tail = *headRef;
// Locate the last node
while(tail->next != NULL)
{
tail = tail->next;
}
tail->next = newNode;
}
}
四、注意:“指针的拷贝” 和 “指针的指针”
指针的拷贝:void PushHead(struct node* headRef, int data) 这样插入节点,对原链表无任何影响。
指针的指针:void PushHead(struct node** headRef, int data)