红桃J

用心写好每行完美的代码,远比写一堆更有价值

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

代码:

 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 
 6  struct ListNode {
 7      int val;
 8      ListNode *next;
 9      ListNode(int x) : val(x), next(NULL) {}
10  };
11 
12 
13  ListNode* rotateRight(ListNode* head, int k) {
14      if (head == NULL)
15          return head;
16      ListNode * p = head;
17      int i = 1;
18      while (p->next != NULL)
19      {
20          p = p->next;
21          i++;
22      }
23      ListNode * tail = p;
24      int L = i;
25      cout << "L = " << L << endl;
26      k = L - k%L;
27      cout << "K = " << k << endl;
28      if (k == L)
29          return head;
30      i = 1;
31      p = head;
32      while (i != k)
33      {
34          p = p->next;
35          i++;
36      }
37      cout << "p ="<<p->val << endl;
38      ListNode *newHead = p->next;
39      p->next = NULL;
40      tail->next = head;
41      return newHead;
42  }
43 
44 
45 
46 
47 int main()
48 {
49     ListNode * head = new ListNode(1);
50     ListNode *p = head;
51     for (int i = 2; i <= 5; i++)
52     {
53         p->next = new ListNode(i);
54         p = p->next;
55     }
56     p = NULL;
57     for (ListNode * temp = head; temp != NULL; temp = temp->next)
58         cout << temp->val << endl;
59     ListNode * newHead = rotateRight(head, 2);
60     cout << "-----------------------------------------" << endl;
61     for (ListNode * temp = newHead; temp != NULL; temp = temp->next)
62         cout << temp->val << endl;
63 }

 

posted on 2015-07-01 16:21  红桃J  阅读(173)  评论(0编辑  收藏  举报