单链表经典算法
1、删除链表中指定的元素
typedef struct ListNode ListNode;
struct ListNode* removeElements(struct ListNode* head, int val) {
// 创建一个空链表
ListNode *newHead, *newTail;
newHead = newTail = NULL;
// 遍历原链表
ListNode* pcur = head;
while (pcur) {
// 找值不为val的节点,尾插到新链表中
if (pcur->val != val) {
// 链表为空
if (newHead == NULL) {
newHead = newTail = pcur;
}
// 链表不为空
else {
newTail->next = pcur;
newTail = newTail->next;
}
}
pcur = pcur->next;
}
if(newTail)
newTail->next = NULL;
return newHead;
}
2、链表的倒置
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head) {
if(head == NULL)
{
return head;
}
//创建三个指针
ListNode*n1,*n2,*n3;
n1=NULL,n2=head,n3=n2->next;
while(n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if(n3)
n3 = n3->next;
}
return n1;
}
3、找出链表中间节点
typedef struct ListNode ListNode;
struct ListNode* middleNode(struct ListNode* head) {
//采用快慢指针
ListNode* slow = head;
ListNode* fast = head;
while(fast && fast->next)//fast要在前面,因为若fast为NULL,则对他解引用会报错,若fast为空,fast在前,就不会执行后面的
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
4、合并两个有序链表——带有哨兵位的链表
typedef struct ListNode ListNode;
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
ListNode* l1 = list1;
ListNode* l2 = list2;
ListNode*newhead,*newtail;
newhead = newtail = (ListNode*)malloc(sizeof(ListNode));//此时链表不为空,头尾指针都指向了没有存储有效数据的有效地址
while(l1 && l2)
{
if((l1->val)<=(l2->val))
{
newtail->next = l1;
newtail = newtail->next;
l1 = l1->next;
}
else
{
newtail->next = l2;
newtail = newtail->next;
l2 = l2->next;
}
}
if(l1)
{
newtail->next = l1;
newtail = newtail->next;
l1 = l1->next;
}
if(l2)
{
newtail->next = l2;
newtail = newtail->next;
l2 = l2->next;
}
if(list1 == NULL)
{
return list2;
}
if(list2 == NULL)
{
return list1;
}
ListNode* ret = newhead->next;
free(newhead);
newhead = NULL;
return ret;
}
5、环形链表的约瑟夫问题
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @param m int整型
* @return int整型
*/
typedef struct ListNode ListNode;
//创建函数节点
ListNode* buynode(int x)
{
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
if(node == NULL)
{
exit(1);
}
node->val = x;
node->next = NULL;
return node;
}
//创建带环链表
ListNode* createCircle(int n)
{
//先创建第一个节点
ListNode* phead = buynode(1);
ListNode* ptail = phead;
for(int i = 2;i<=n;i++)
{
ptail->next = buynode(i);
ptail = ptail->next;
}
ptail->next = phead;
return ptail;
}
//销毁链表
void destroy(ListNode* ps)
{
free(ps);
ps = NULL;
}
int ysf(int n, int m ) {
// write code here
//根据n创建代还链表
ListNode* prev = createCircle(n);
ListNode *pcur = prev->next ;
//开始报数自杀
int count = 1;
while(prev->next != prev)
{
if(count == m)
{
prev->next = pcur->next;
destroy(pcur);
pcur = prev->next;
count = 1;
}
else
{
//此时不需要销毁
count++;
prev = pcur;
pcur = pcur->next;
}
}
return prev->val;
}