(1)删除链表中等于给定值val的所有节点
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
(2)删除链表中重复的结点
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。
例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
(3)从尾到头打印链表
//笔试题:
/*
删除链表中等于给定值val的所有节点。
样例:
给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。
*/
struct Node{
int value;
Node* next;
};
Node* CreatNode(int value, Node* next = NULL){
Node* node = new Node;
node->value = value;
node->next = next;
return node;
}
Node* Delete(Node* head, int x){
if (head == NULL){
return head;
}
Node* prev = head;
Node* cur = head->next;
while (cur != NULL){
if (x == cur->value){
prev->next = cur->next;
cur = cur->next;
}
else{
prev = cur;
cur = cur->next;
}
}
if (x == head->value){
head = head->next;
}
return head;
}
//打印链表
void PrintList(Node* head){
Node* curr = head;
while (curr != NULL){
cout << curr->value << ends;
curr = curr->next;
}
cout << endl;
}
//面试题5:从尾到头打印链表
void PrintListFromTail(Node* head){
if (head == NULL){
return;
}
else{
PrintListFromTail(head->next);
cout << head->value << ends;
}
}
测试
void test(){
Node* g = CreatNode(5);
Node* f = CreatNode(4,g);
Node* e = CreatNode(4,f);
Node* d = CreatNode(3,e);
Node* c = CreatNode(3,d);
Node* b = CreatNode(2,c);
Node* a = CreatNode(1,b);
PrintList(a);
Node* head=Delete(a, 3);
PrintList(head);
cout << endl;
PrintListFromTail(head);
}
//删除已排序链表中重复的结点,重复节点不保留。
Node* DeleteDuplication(Node* head){
if (head == NULL){
return head;
}
Node* first = new Node; //新建一个头结点就简单很多了
first->next = head;
Node* last = first;
Node* curr = head;
while (curr != NULL & curr->next != NULL){
if (curr->value == curr->next->value){
int v = curr->value;
while (v == curr->value){
curr = curr->next;
}
last->next = curr;
}
else{
last = curr;
curr = curr->next;
}
}
return first->next;
}