您的位置:首页 > 其它

头插法和尾插法建立带头节点的单链表

2016-04-12 11:49 267 查看
有两种方法建立单链表,尾插法和头插法,他们的区别是:头插法是按照输入元素倒序建立,为尾插法为顺序插入,并且多一个尾节点,我们一般使用尾插法。

一.头插法



代码为:

pCurr -> next = pHead -> next;
pHead -> next = pCurr;


二.尾插法



pTail -> next = pCurr;
pTail = pCurr;


完整代码如下:

//头插法和尾插法建立单链表及
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
Node* next;
};
void tailInvert(int* data);
void headInvert(int* data);
int main() {
int data[5] = {1, 2, 3, 4, 5};
tailInvert(data);
printf("\n");
headInvert(data);

}

void tailInvert(int* data) {
Node* pHead = (Node*)malloc(sizeof(Node));
Node* pCurr = NULL;
Node* pTail = pHead;

for(int i = 0; i < 5; ++i) {
pCurr = (Node*)malloc(sizeof(Node));
pCurr -> data = data[i];
pTail -> next = pCurr; pTail = pCurr;
}
pTail -> next = NULL;
printf("尾插法:\n");
for(int j = 0; j < 5; ++j) {
printf("%d\t", pHead -> next -> data);
pHead = pHead -> next;
}
}

void headInvert(int* data)
{
Node* pHead = (Node*)malloc(sizeof(Node));
pHead -> next = NULL;
Node* pCurr = NULL;
for(int i = 0; i < 5; ++i) {
pCurr = (Node*)malloc(sizeof(Node));
pCurr -> next = pHead -> next; //巧妙
pCurr -> data = data[i];
pHead ->next = pCurr;
}
printf("头插法:\n");
for(int j = 0; j < 5; ++j) {
printf("%d\t", pHead -> next -> data);
pHead = pHead -> next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: