首页 > 编程语言 > 详细

重新排序链表

时间:2016-06-15 14:22:08      阅读:242      评论:0      收藏:0      [点我收藏+]

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode * reorder(ListNode *phead)//链表的反转
{
  if(phead==NULL || phead->next==NULL)
    return phead;
  ListNode *p=phead;
  ListNode *q=p->next;
  ListNode *s=q->next;
  while(q)
  {
  q->next=p;
  p=q;
  q=s;
  s=s->next;
  }
  phead->next=NULL;
  phead=p;
  return phead;
}
ListNode *getmid(ListNode *head)//取得链表的中点
{
  if(head==NULL || head->next==NULL)
    return head;
  ListNode *p=head;
  ListNode *q=head;
  while(q&&q->next)
  {
  p=p->next;
  q=q->next->next;
  }
return p;
}
ListNode * mergeList(ListNode *l1,ListNode *l2)//合并链表
{
  if(l1==NULL)
    return l2;
  if(l2==NULL)
    return l1;
  int count=1;
  ListNode *head=new ListNode(0);
  ListNode *p=head;
  while(l1!=NULL && l2!=NULL)
  {
  if(count%2==1)
  {
  p->next=l1;
  l1=l1->next;

  }else
  {
  p->next=l2;
  l2=l2->next;
  }
  count++;
  p=p->next;
  }
  if(l1!=NULL)
    p->next=l1;
  if(l2!=NULL)
    p->next=l2;
  return head->next;
}

void reorderList(ListNode *head) {
  if(head==NULL || head->next==NULL)
    return;
  ListNode *mid=getmid(head);
  ListNode *phead=reorder(mid->next);
  mid->next=NULL;
  head=mergeList(head,phead);


}
};

重新排序链表

原文:http://www.cnblogs.com/ranranblog/p/5587166.html

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