链表|遍历|插入|

参考资料 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)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值