将链表节点序号(不是值)是偶数的放到链表后面, 如
Given 1->2->3->4->5->NULL
,
return 1->3->5->2->4->NULL
.
我首先统计了下链表的大小cnt,同时求出链表尾端end,
然后直接将每个链表节点序号是奇数的点后面的节点放到end后面去,
同时更新end,这样更新cnt/2次。
注意点:当链表长度小于 3的时候不需要做这样的操作。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* oddEvenList(ListNode* head) { 12 if(!head) return head; 13 ListNode* last = head; 14 int cnt = 1; 15 for(; last->next; last = last->next, ++cnt); 16 if(cnt < 3) return head; 17 ListNode* now = head; 18 ListNode* end = last; 19 20 for(int i = 0; i< cnt/2; now = now->next, ++i){ 21 22 ListNode* next = now->next; 23 now->next = next->next; 24 25 end->next = next; 26 next->next = NULL; 27 28 end = next; 29 30 } 31 return head; 32 } 33 };
这里在附上一段测试代码
1 int main(){ 2 int n; 3 while(scanf("%d",&n)){ 4 ListNode* head = new ListNode(1); 5 ListNode* node= head; 6 for(int i = 2; i<=n; ++i ){ 7 ListNode* now = new ListNode(i); 8 node->next = now; 9 node = now; 10 } 11 Solution s; 12 s.oddEvenList(head); 13 for(node = head; node; node = node ->next){ 14 printf("%d ",node->val); 15 } 16 puts(""); 17 for(node = head; node; ){ 18 ListNode* now = node; 19 node = node ->next; 20 delete now; 21 } 22 } 23 }