单链表面试题——基础篇

来源:互联网 发布:java自增id生成策略 编辑:程序博客网 时间:2024/06/04 20:14

顺序表和链表的优缺点

1:顺序表可以进行随机访问,链表不行。
2:顺序表尾插效率高,头插(删)或者中间位置插入(删除)时链表效率更高。
3:顺序表的CPU高速缓存利用率高,链表的CPU高速缓存利用率低。

顺序表和链表的适用场景

    适用于需要大量访问元素的 而少量增添/删除元素的程序;
   适用于需要进行大量增添/删除元素操作 而对访问元素无要求的程序。


#pragma once
typedef int DataType;
typedef struct Node
{
 DataType data;
 struct Node* next;
}Node;
Node* BuyNode(DataType x)
{
 Node* node = (Node*)malloc(sizeof(Node));
 node->data = x;
 node->next = NULL;
 return node;
}
void PrintTailToHead(Node* head)
{
 if (head == NULL)
  return;
 PrintTailToHead(head->next);
 printf("%d ", head->data);
}
void EraseNonTail(Node* pos)
{
 Node* next;
 assert(pos && pos->next);
 next = pos->next;
 pos->data = next->data;
 pos->next = next->next;
 free(next);
}
void InsertFront(Node* pos, DataType x)
{
 Node* next, *tmp;
 assert(pos);
 next = pos->next;
 tmp = BuyNode(pos->data);
 pos->data = x;
 pos->next = tmp;
 tmp->next = next;
}
Node* Josephus(Node* hus, int k)
{
 Node* man, *next;
 assert(hus);
 man = hus;
 while (man->next != man)
 {
  int count = k;
  while (--count)
  {
   man = man->next;
  }
  next = man->next;
  man->data = next->data;
  man->next = next->next;
  free(next);
 }
}
void ReverseList(Node** ppHead, DataType x)
{
 Node* n0, *n1, *n2;
 if (*ppHead == NULL)
 {
  return;
 }
 n0 = NULL;
 n1 = *ppHead;
 n2 = (*ppHead)->next;
 while (n1)
 {
  n1->next = n0;
  n0 = n1;
  n1 = n2;
  if (n2)
   n2 = n2->next;
 }
 *ppHead = n0;
}
void SortList(Node* pHead)
{
 if (pHead == NULL || pHead->next == NULL)
  return;
 Node* tail = NULL;
 while (tail != NULL)
 {
  int exchange = 0;
  Node* cur = pHead, *next = cur->next;
  while (next != cur)
  {
   if (cur->data > next->data)
   {
    exchange = 1;
    DataType tmp = cur->data;
    cur->data = next->data;
    next->data = tmp;
   }
   cur = cur->next;
   next = next->next;
  }
  if (exchange == 0)
  {
   break;
  }
  tail = cur;
 }
}
Node* MergeList(Node* list1, Node* list2)
{
 Node* list, *tail;
 if (list1 == NULL)
  return list2;
 if (list2 == NULL)
  return list1;
 if (list1->data < list2->data)
 {
  list = list1;
  list1 = list1->next;
 }
 else
 {
  list = list2;
  list2 = list2->next;
 }
 tail = list;
 while (list1&&list2)
 {
  if (list1->data < list2->data)
  {
   tail->next = list1;
   list1 = list1->next;
  }
  else
  {
   tail->next = list2;
   list2 = list2->next;
  }
  tail = tail->next;
 }
 if (list1)
  tail->next = list1;
 if (list2)
  tail->next = list2;
 return list;
}