您的位置:首页 > 职场人生

面试题—链表操作

2016-01-27 20:38 579 查看
链表是最基本的数据结构,也是面试中较为常见的问题,链表的一些基本操作功能是必须能够实现,下面是一些关于链表基本的操作。
——链表的节点设置
typedef int Datatype;
typedef struct SListNode
{
Datatype data;      //数据域
struct SListNode *next;         //next指针域
}SListNode;

——链表的基本操作
(1)删除一个无头单链表的非尾节点
(2)在无头单链表的一个非头结点前插入一个节点
(3)查找单链表的中间节点,要求只能遍历一次链表
(4)查找单链表的倒数第k个节点,要求只能遍历一次单链表
(5)从尾到头打印单链表(使用递归,压入堆栈)
(6)逆置单链表,不能创建节点

//利用头插法建立单链表
void Frontinsert(SListNode *&phead)
{
SListNode *tmp = (SListNode *)malloc(sizeof(SListNode));
}

//删除一个无头单链表的非尾节点
void DelNonTailNode(SListNode *pos)
{
assert(pos);
assert(pos->next);    //非尾节点
SListNode *del = pos->next;
pos->data = del->data;
pos->next = del->next;
free(del);
}

//在无头单链表的一个非头结点前插入一个节点
void insertFrontNode(SListNode *pos, Datatype x)
{
assert(pos);
SListNode *tmp = _BuyNode(x);
tmp->next = pos->next;
pos->next = tmp;
Datatype tmpdata = pos->data;
pos->data = tmp->data;
tmp->data = tmpdata;
}

//查找单链表的中间节点,要求只能遍历一次链表
SListNode * FindMidNode(SListNode * phead)
{
SListNode *fast = phead;
SListNode *slow = phead;
while (fast)
{
if (fast->next != NULL)
{
fast = fast->next->next;
}
else
{
break;
}
slow = slow->next;
}
return slow;
}

//查找单链表的倒数第k个节点,要求只能遍历一次单链表
SListNode * FindKNode(SListNode *phead, Datatype k)
{
SListNode *fast = phead;
SListNode *slow = phead;
while (fast && k--)
{
fast = fast->next;
}
if (fast == NULL)
{
return NULL;
}
while (fast)
{
fast = fast->next;
slow = slow->next;
}
return slow;
}

//从尾到头打印单链表(使用递归,压入堆栈)
void printTailToHead(SListNode *phead)
{
if (phead == NULL)
{
return;
}
else
{
printTailToHead(phead->next);
printf("%d ", phead->next);
}
}

//逆置单链表,不能创建节点
SListNode *Reverse(SListNode *phead)
{
SListNode *cur = phead;
SListNode *newhead = NULL;
while (cur)
{
SListNode *tmp = cur;
cur = cur->next;
tmp->next = newhead;
}
return phead;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息