链表是基本却非常重要的数据结构,经常在面试中出现,现在我主要是针对面试中出现比率非常高的链表逆转及链表排序给出自己的源码仅供参考。
另外,如果觉得我写的好,可以关注我的github帐号(https://github.com/chenqiangzhishen). 本文代码部分我也贴在了如下的目录中。
(https://github.com/chenqiangzhishen/Algorithms/blob/master/linkList/linkListActionSet.c)
有了github,我会经常更新些新的,高效的,经典的算法和其他新的知识与大家分享,开源快乐~
注:我的代码不出意外,都可以直接运行,采用gcc/g++/gdb进行的开发与调试工具及vim开发工具。
因为比较喜欢在Linux下编程,不大喜欢用中文切来切去的进行描述,所以直接采用英文进行注释。
#include <stdio.h>
#include <stdlib.h>
typedef struct LinkList {
int data;
struct LinkList *next;
} Node;
Node* createLinkList(int n)
{
if(n <= 0)
{
printf("Please input the number of Node bigger than 0
");
return;
}
Node *head=NULL, *pre=NULL, *behind=NULL;
head=(Node *)malloc(sizeof(Node));
if(head == NULL)
{
printf("Allocated memory error
");
return;
}
head->next = NULL;
pre = head;
printf("Please input the data
");
while(n-- >0)
{
behind = (Node*)malloc(sizeof(Node));
if(behind != NULL)
{
scanf("%d", &behind->data);
pre->next = behind;
pre = behind;
}
}
behind->next=NULL;
return head;
}
void printLinkList(Node *head)
{
if(head == NULL)
return;
Node *temp = head->next;
while(temp)
{
if(temp->next)
{
printf("%d->",temp->data);
} else {
printf("%d
", temp->data);
}
temp = temp->next;
}
}
//LinkList with head node.
Node* reverseLinkList(Node *head)
{
if(!head || !head->next)
return;
Node *p=NULL, *q=NULL, *r=NULL;
p = head->next;
q = p->next;
p->next = NULL;//the last node ends with NULL
while(q)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
head->next = p;
return head;
}
//select sort for link list.
//just sort the data part of each Node.
Node* sortLinkList(Node* head)
{
if(head==NULL || head->next==NULL)
return head;
Node* minNode = NULL;
Node* q = NULL;
Node* p = head->next;
Node* firstNode = p;
while(p)
{
minNode = p;
q = p->next;
while(q)
{
if(q->data < minNode->data)
{
minNode = q;
}
q = q->next;
}
if(minNode->data != p->data)
{
p->data ^= minNode->data;
minNode->data ^= p->data;
p->data ^= minNode->data;
}
p = p->next;
}
head->next = firstNode;
return head;
}
int main(void)
{
int n=0;
printf("Input the number of Node you want to create
");
scanf("%d", &n);
Node * linkList = createLinkList(n);
printf("The origin LinkList is:
");
printLinkList(linkList);
printf("The LinkList after reversing is:
");
printLinkList(reverseLinkList(linkList));
printf("The LinkList after sort is:
");
printLinkList(sortLinkList(linkList));
return 0;
}