数据结构:
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node *next;
}Node,* LinkList;
1、从尾到头打印单链表
void TailToFrontPrint(LinkList head)
/*从尾到头打印单链表*/
{
if (head != NULL)
{
TailToFrontPrint(head->next);
printf("%d ", head->data);
}
}
2、删除一个无头单链表的非尾结点
void DelNoneTailNode(Node *pos)
/*删除一个无头单链表的非尾结点*/
{
assert(pos);
if (pos->next == NULL)
{
return;
}
Node *del = pos->next;
pos->data = del->data;
pos->next = del->next;
free(del);
del = NULL;
}
3、在无头单链表的一个非头结点前插入一个结点
void InsNoneFrontNode(Node *pos,DataType x)
/*在无头单链表的一个非头结点前插入一个结点*/
{
Node *s = (Node *)malloc(sizeof(Node));
s->data = pos->data;
pos->data = x;
s->next = pos->next;
pos->next = s;
}
4、逆置/反转单链表
void ReverseNode(LinkList &head)
/*反转单链表*/
{
Node *front = NULL;
Node *tmp = head;
Node *start = NULL;
while (tmp != NULL)
{
start = tmp->next;
tmp->next = front;
front = tmp;
tmp = start;
}
head = front;
}
5、查找单链表的中间节点,要求只遍历一次链表
Node * FindMidNode(LinkList head)
/*查找单链表的中间结点*/
{
Node *slow = head;
Node *fast = head;
while (fast && fast->next)
{
fast = fast->next->next;
if (fast == NULL)
/*有if偶数时返回较小,无if返回较大*/
{
break;
}
slow = slow->next;
}
return slow;
}
6、查找单链表的倒数第k个结点,要求只遍历一次链表
Node * FindKNode(LinkList head, int k)
/*返回倒数第k个结点*/
{
assert(head);
/*1、k大于head的长度
2、*/
Node *slow = head;
Node *fast = head;
while (k--)
{
if (fast == NULL)
{
return NULL;
}
else
{
fast = fast->next;
}
}
while (fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
转载于:https://blog.51cto.com/10740026/1731038