【剑指offer 面试题13】在 O(1) 时间删除链表结点
2015-06-20 15:13
746 查看
#include <iostream> using namespace std; //构造链表结点 struct ListNode { int val; ListNode *next; ListNode(int v = 0):val(v), next(NULL){}; }; //打印结点 void printList(ListNode *head) { while(head != NULL) { cout<<head->val<<" "; head = head->next; } cout<<endl; } //删除结点 void deleteListNode(ListNode **head, ListNode *tobeDeleted) { //头结点或者待删除结点为空,则结束调用 if(*head == NULL || tobeDeleted == NULL) return ; //待删除结点的pnext非空,则复制其值到待删除结点,删除pnext if(tobeDeleted->next != NULL) { ListNode *pnext = tobeDeleted->next; tobeDeleted->val = pnext->val; tobeDeleted->next = pnext->next; delete pnext; pnext = NULL; } //若只剩头结点,则删除头结点 else if(tobeDeleted == *head) { delete tobeDeleted; tobeDeleted = NULL; *head = NULL; } //若待删除结点为尾结点,则顺序查找后删除 else { ListNode *phead = *head; while(phead->next != tobeDeleted) { phead = phead->next; } phead->next = NULL; delete tobeDeleted; tobeDeleted = NULL; } } int main() { ListNode *ls = new ListNode(0); ListNode *head = ls; ListNode *l1 = new ListNode(1); ls->next = l1; ls = ls->next; ListNode *l2 = new ListNode(2); ls->next = l2; ls = ls->next; ListNode *l3 = new ListNode(3); ls->next = l3; ls = ls->next; ListNode *l4 = new ListNode(4); ls->next = l4; ls = ls->next; cout<<"初始链表 -> "; printList(head); cout<<endl; cout<<"删除中间结点2后 -> "; deleteListNode(&head,l2); printList(head); cout<<endl; cout<<"删除尾结点4后 -> "; deleteListNode(&head,l4); printList(head); cout<<endl; cout<<"删除中间结点1后 -> "; deleteListNode(&head,l1); printList(head); cout<<endl; cout<<"删除尾结点3后 -> "; deleteListNode(&head,l1); printList(head); cout<<endl; cout<<"删除头结点后 -> "; deleteListNode(&head,head); printList(head); cout<<endl; }
测试结果:
初始链表 -> 0 1 2 3 4 删除中间结点2后 -> 0 1 3 4 删除尾结点4后 -> 0 1 3 删除中间结点1后 -> 0 3 删除尾结点3后 -> 0 删除头结点后 ->
相关文章推荐
- 读《人,绩效和职业道德》有感
- 黑马程序员--java学习笔记第八天
- 黑马程序员——JAVA笔记——静态static
- 【剑指offer】面试题17、合并两个排序的链表
- 【剑指offer】面试题16、反转链表
- 黑马程序员——Java基础——String类的学习
- 黑马程序员--java学习笔记第七天
- 程序员技术练级攻略(皓哥)
- vim的学习小小笔记
- 黑马程序员——IO流(一)
- 黑马程序员——Java基础---面向对象 (概述及封装等)
- 黑马程序员——JAVA笔记——单例设计模式
- 黑马程序员--JAVA学习笔记第六天
- 去哪儿科技实习生面试总结【通过面试】
- 黑马程序员——JAVA笔记——String类
- 《人,绩效和职业道德》读后感
- 黑马程序员——集合(二)
- 黑马程序员——集合(一)
- 黑马程序员--面向对象细节知识点--3rd day
- 黑马程序员---多态