单链表的结构
typedef struct SListNode
{
int data;
struct SListNode* next;
}SLN;
节点的创建
SLN* BuySListNode(int x)
{
SLN* newnode = (SLN*)malloc(sizeof(SLN));
assert(newnode);
newnode->data = x;
newnode->next = NULL;
return newnode;
}
头部插入
void SLTPushFront(SLN** pphead, int x)
{
SLN* phead = *pphead;
SLN* newnode = BuySListNode(x);
*pphead = newnode;
newnode->next = phead;
}
头部删除
void SLTPopFront(SLN** pphead)
{
assert(*pphead != NULL);
SLN* cur = (*pphead)->next;
free(*pphead);
*pphead = cur;
}
中间插入
void SLTInsetNode(SLN**pphead,SLN*dst,int x)
{
assert(dst);
assert(pphead);
if (*pphead == dst)
{
SLTPushFront(*pphead,x);
}
else
{
SLN* newnode = BuySListNode(x);
newnode->next = dst;
SLN* cur = *pphead;
while (cur->next != dst)
{
cur = cur->next;
}
cur->next = newnode;
}
}
中间删除
void SLTErase(SLN** pphead, SLN* dst)
{
assert(pphead);
assert(dst);
if (*pphead != dst)
{
SLTPopFront(pphead);
}
else
{
SLN* prev = *pphead;
while (prev->next != dst)
{
prev = prev->next;
}
prev->next = dst->next;
free(dst);
}
}
尾部插入
void SLTPushBack(SLN** pphead, int x)
{
SLN* newnode = BuySListNode(x);
if (*pphead == NULL)
{
*pphead = newnode;
}
else
{
SLN* tail = *pphead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = newnode;
}
}
尾部删除
void SLTPopBack(SLN** pphead)
{
assert(*pphead);
SLN* tail = *pphead;
if ((*pphead)->next==NULL)
{
free(*pphead);
*pphead = NULL;
}
else
{
while (tail->next->next != NULL)
{
tail = tail->next;
}
free(tail->next);
tail->next = NULL;
}
}
链表练习
合并两个有序链表
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
if (list1 == NULL)
return list2;
if (list2 == NULL)
return list1;
struct ListNode* head, * tail;
head = tail = NULL;
while (list1 && list2)
{
if ((list1->val) < (list2->val))
{
if (tail == NULL)
{
head = tail = list1;
}
else
{
tail->next = list1;
tail = list1;
}
list1 = list1->next;
}
else
{
if (tail == NULL)
{
head = tail = list2;
}
else
{
tail->next = list2;
tail = list2;
}
list2 = list2->next;
}
}
if (list1)
tail->next = list1;
if (list2)
tail->next = list2;
return head;
}
链接:21. 合并两个有序链表 - 力扣(LeetCode)
链表中倒数第k个节点
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k) {
// write code here
struct ListNode* lower, * fast;
lower = fast = pListHead;
for (int i = 0; i < k; i++)
{
while (fast == NULL)
return NULL;
fast = fast->next;
}
while (fast)
{
fast = fast->next;
lower = lower->next;
}
return lower;
}
链接:链表中倒数第k个结点__牛客网 (nowcoder.com)
移除链表元素
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode*cur=head;
struct ListNode*precur=head;
while(cur)
{
if(cur->val==val)
{
if(cur==head)
{
head=cur->next;
free(cur);
cur=head;
}
else
{
precur->next=cur->next;
free(cur);
cur=precur->next;
}
}
else
{
precur=cur;
cur=cur->next;
}
}
return head;
}
反转链表
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* cur=head;
if(head==NULL)
cur=NULL;
struct ListNode* next=head;
head=NULL;
while(cur)
{
next=cur->next;
cur->next=head;
head=cur;
cur=next;
}
return head;
}