首页 > 其他 > 详细

《Cracking the Coding Inteview》——第2章:链表——题目3

时间:2014-03-18 11:55:32      阅读:491      评论:0      收藏:0      [点我收藏+]

2014-03-18 02:25

题目:给定一个单链表中间的节点,删掉那个节点。

解法:把后面节点的数据域拷到当前节点来,然后删除后面那个节点。当前节点不是尾巴,所以后面不为空。

代码:

bubuko.com,布布扣
 1 // 2.2 Remove a node from middle of a linked list
 2 #include <cstdio>
 3 using namespace std;
 4 
 5 struct ListNode {
 6     int val;
 7     struct ListNode *next;
 8     ListNode(int x): val(x), next(nullptr) {};
 9 };
10 
11 class Solution {
12 public:
13     void deleteThatNode(ListNode *ptr) {
14         if (ptr != nullptr && ptr->next != nullptr) {
15             struct ListNode *tmp = ptr->next;
16             ptr->val = tmp->val;
17             ptr->next = tmp->next;
18             delete tmp;
19         }
20     }
21 };
22 
23 int main()
24 {
25     int i;
26     int n, k;
27     int val;
28     struct ListNode *head, *ptr;
29     Solution sol;
30     
31     while (scanf("%d", &n) == 1 && n > 0) {
32         // create a linked list
33         ptr = head = nullptr;
34         for (i = 0; i < n; ++i) {
35             scanf("%d", &val);
36             if (head == nullptr) {
37                 head = ptr = new ListNode(val);
38             } else {
39                 ptr->next = new ListNode(val);
40                 ptr = ptr->next;
41             }
42         }
43         
44         // remove a node from middle of the list
45         scanf("%d", &k);
46         k = k < 1 ? 1 : k;
47         k = k > n ? n : k;
48         ptr = head;
49         for (i = 1; i < k; ++i) {
50             ptr = ptr->next;
51         }
52         sol.deleteThatNode(ptr);
53         
54         // print the list
55         printf("%d", head->val);
56         ptr = head->next;
57         while (ptr != nullptr) {
58             printf("->%d", ptr->val);
59             ptr = ptr->next;
60         }
61         printf("\n");
62         
63         // delete the list
64         while (head != nullptr) {
65             ptr = head->next;
66             delete head;
67             head = ptr;
68         }
69     }
70     
71     return 0;
72 }
bubuko.com,布布扣

《Cracking the Coding Inteview》——第2章:链表——题目3,布布扣,bubuko.com

《Cracking the Coding Inteview》——第2章:链表——题目3

原文:http://www.cnblogs.com/zhuli19901106/p/3606689.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!