链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。而单向链表就是在每一个结点中除了保存的数据之外只有一个指向下一个节点的指针。双向链表的每一个节点除了保存的数据之外,即有指向下一个节点的指针还有指向上一个节点的指针。
单链表节点的关系似乎像无间道中的人物关系,只有你的上级(上一个节点)知道你,你的上级能找到你而你却找不到他。所以整个过程中要想让别知道自己存在就必须确保你的上级(上一个结点)没有挂了,如果你的上级找不到了并且他没有把你的关系告诉别人(用另一个指针保存),那么你也就挂掉了。
创建单向链表
反转链表
#include <stdio.h>
#include <stdlib.h>
typedef struct data {
int data;
struct data *nextPoint;
}CustomData;
CustomData* createLink(int a[10], int n) {
CustomData *head = NULL;
CustomData *p = NULL;
for (int i = 0; i < n; i++) {
CustomData *temp= (CustomData *)malloc(sizeof(CustomData));
temp -> data = a[i];
temp->nextPoint = NULL;
if (head == NULL) {
head = temp;
p = head;
} else {
p ->nextPoint = temp;
p = temp;
}
}
return head;
}
CustomData * reverseLink(CustomData *link) {
CustomData *tempHead = link;
CustomData *next = NULL;
CustomData *pre = NULL;
while (tempHead) {
if (tempHead == link) {
next = tempHead->nextPoint;
tempHead ->nextPoint = NULL;
pre = tempHead;
} else {
next = tempHead->nextPoint;
tempHead -> nextPoint = pre;
pre = tempHead;
}
tempHead = next;
if (tempHead != NULL) {
printf("%d\n",tempHead ->data);
}
}
return pre;
}
int main(int argc, const char * argv[]) {
// insert code here...
int a [10] = {1,2,3,4,5,6,7,8,9,10};
CustomData *head = createLink(a, 10);
head = reverseLink(head);
while (head) {
printf("%d", head->data);
head = head->nextPoint;
}
return 0;
}