2014-03-18 02:24

题目:给定一个单链表,找出倒数第K个节点。

解法:让一个指针先走K步,然后俩指针一起走到尽头。当然也可以先走到尽头数出链表的长度,然后第二次少走K步。其实耗费的工夫是一样的,但貌似总有人觉得第一种方法很巧妙很优美。

代码:

 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     ListNode* findKthNode(ListNode *head, int k) {
14         if (head == nullptr || k < 1) {
15             return head;
16         }
17         struct ListNode *p1, *p2;
18         
19         p1 = p2 = head;
20         int i;
21         for (i = 0; i < k; ++i) {
22             p2 = p2->next;
23             if (p2 == nullptr) {
24                 return head;
25             }
26         }
27         while (p2 != nullptr) {
28             p1 = p1->next;
29             p2 = p2->next;
30         }
31         
32         return p1;
33     }
34 };
35 
36 int main()
37 {
38     int i;
39     int n, k;
40     int val;
41     struct ListNode *head, *ptr;
42     Solution sol;
43     
44     while (scanf("%d", &n) == 1 && n > 0) {
45         // create a linked list
46         ptr = head = nullptr;
47         for (i = 0; i < n; ++i) {
48             scanf("%d", &val);
49             if (head == nullptr) {
50                 head = ptr = new ListNode(val);
51             } else {
52                 ptr->next = new ListNode(val);
53                 ptr = ptr->next;
54             }
55         }
56         
57         // find the kth node from the end of the list
58         scanf("%d", &k);
59         ptr = sol.findKthNode(head, k);
60         printf("%d\n", ptr->val);
61         
62         /*
63         // print the list
64         printf("%d", head->val);
65         ptr = head->next;
66         while (ptr != nullptr) {
67             printf("->%d", ptr->val);
68             ptr = ptr->next;
69         }
70         printf("\n");
71         */
72         
73         // delete the list
74         while (head != nullptr) {
75             ptr = head->next;
76             delete head;
77             head = ptr;
78         }
79     }
80     
81     return 0;
82 }

 

 posted on 2014-03-18 02:25  zhuli19901106  阅读(306)  评论(0编辑  收藏  举报