面试题—链表操作

来源:互联网 发布:懒人做饭知乎 编辑:程序博客网 时间:2024/05/21 05:07

        链表是最基本的数据结构,也是面试中较为常见的问题,链表的一些基本操作功能是必须能够实现,下面是一些关于链表基本的操作。

       ——链表的节点设置

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;}


本文出自 “无心的执着” 博客,谢绝转载!

0 0
原创粉丝点击