理解C语言里是如何构造出链表的
链表的概念
数据元素随机存储在内存中,通过指针维系数据间“一对一”逻辑关系的存储结构为链表。
如何构造链表
链表的基本单位是结点。
每一个结点都配有一个指针。
因此可以给出C语言链表定义:
typedef struct link{
char elem;
struct link* next;
}Link;
在LeetCode里一般采用如下形式:
struct ListNode {
int val;
struct ListNode* next;
};
如果要创建一个值为0 1 2 3 4 的链表,可以这么做:
struct ListNode* initLink() {
int i;
struct ListNode* p = NULL;//头节点
struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = 0;
temp->next = NULL;
p = temp;
for (i = 1;i < 5;i++) {
struct ListNode* a = (struct ListNode*)malloc(sizeof(struct ListNode));
a->val = i;
a->next = NULL;
temp->next = a;
temp = temp->next;
}
return p;
}
链表的增删改查
遍历链表
不要只顾当前位置而将标记标头的指针丢掉!
//打印链表
void printList(struct ListNode* p) {
struct ListNode* temp = p;
while (temp) {
printf("%d",temp->val);
temp = temp->next;
}
printf("\n");
}
//获取链表长度
int getLength(struct ListNode* p) {
struct ListNode* temp1 = p;
int length = 0;
while (temp1) {
struct ListNode* f = temp1;
length++;
temp1 = temp1->next;
free(f);
}
return length;
}
链表插入
表头插入
head指针永远要指向表头!
new->next=head;
head=new;
中间插入
顺序很重要,不能颠倒
//pNode为前指针
new->next=pNode->next;
pNode->next=new;
结尾插入
插入指针要指向NULL,其余与中间插入相似
//链表插入
struct ListNode* insertNode(struct ListNode* head, struct ListNode* nodeInsert, int position) {
if (head == NULL) {
return nodeInsert;
}
int size = getLength(head);
if (position > size + 1 || position < 1) {
printf("位置参数越界");
return head;
}
//插入首部
if (position == 1) {
nodeInsert->next = head;
head = nodeInsert;
return head;
}
struct ListNode* pNode = head;
int count = 1;
//遍历链表,找到插入位置前一个节点
while (count < position - 1) {
pNode = pNode->next;
count++;
}
nodeInsert->next = pNode->next;
pNode->next = nodeInsert;
return head;
}
链表删除
头部删除
head=head->next;
尾部删除
cur->next=NULL;
中间删除
...tmp=cur->next;
cur->next=tmp->next
问题:cur->next=cur->next->next;可以用这句代码吗?
可以!
//链表删除
struct ListNode* deleteNode(struct ListNode* head, int position) {
if (head == NULL) {
return NULL;
}
int size = getLength(head);
if (position > size + 1 || position < 1) {
printf("位置参数越界");
return head;
}
//删除首部
if (position == 1) {
struct ListNode* curNode = head;
head = head->next;
free(curNode);
return head;
}
else {
struct ListNode* cur = head;
int count = 1;
//遍历链表,找到插入位置前一个节点
while (count < position - 1) {
cur = cur->next;
count++;
}
struct ListNode* tmp = cur->next;
cur->next = tmp->next;
free(tmp);
return head
}
}
第一次在csdn上做笔记有点小紧张呢!