整理一些面试当中经常遇到的问题 帮助自己记忆.
链表的类型: 单向链表,双向链表,循环链表
C++ 链表的例子
typedef struct IntElement {
struct IntElement *next;
int data;
} IntElement;
c# 实现
public class LinkNode {
public LinkNode Next;
public object Data;
}
操作链表常犯的错误:
C#
public void insertInFront( LinkNode list, Object data){
LinkNode temp = new LinkNode();
temp.Data = data;
temp.next = list;
}
错误原因是没有更新Header的引用, 解决的办法是使用引用参数 ref LinkNode 或者是返回新的头节点
C++
bool insertInFront(IntElement *head, int data){
IntElement *newElement = new IntElement();
if(!newElement) return false;
newElem -> data = data;
head = newElem;
return true;
}
正确的方法应该是:
IntElement * insertInFront(IntElement *head, int data){
IntElement *newElement = new IntElement();
if(!newElement) return false;
newElem -> data = data;
newElem -> next = *head -> next;
return newElem;
}
删除单链表的节点:
bool deleteElement(IntElement** head, IntElement* deleteMe)
{
IntElement* element = *head;
if(*head == deleteMe){
*head = element ->next;
delete deleteMe;
return true;
}
while(element){
if(element-> next == deleteMe){
element->next = deleteMe->next;
delete deleteMe;
return true;
}
element = element->next;
}
return false;
}
删除整个链表
public void CleanList(IntElement** head){
IntElement* element = *head;
while(element){
IntElement* next = element->next;
delete element;
element = next;
}
*head = NULL;
}
使用单链表实现一个栈.