美团面试算法题

1. Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.zhi
Given 1->1->1->2->3
ListNode* deleteElements(ListNode *head)
{
    if(head==NULL&&head->next==NULL)
        return head;
    ListNode *p=head;
    ListNode *q=p->next;
    while(q)
    {
        if(p->val!=q->val)
        {
            listNode *del=p->next;
            while(del!=q)
            {
                ListNode *tmp=del->next;
                delete del;
                del=tmp;
            }
            p->next=q;
            p=q;
            q=q->next;
        }
        else
        {
            q=q->next;
        }
    }
    p->next=NULL;
    return head;
}

2. 打印杨辉三角
     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1
 
 输入:n, 打印前n行,不用考虑缩进
 
 void print(int n)
 {
     if(n<=0)
         return;
     if(n==1)
     {
         cout<<1<<endl;
         return;
     }
     if(n==2)
     {
         count<<1<<' '<<1<<endl;
         return;
     }
     vector<int> res={1,1};
     cout<<1<<endl;
     cout<<1<<' '<<1<<endl;
     for(int i=3;i<=n;++i)
     {
          vector<int> tmp;
          tmp.push_back(1);
          for(int j=0;j<res.size()-1;++j)
          {
              tmp.push_back(res[j]+res[j+1]);
          }
          tmp.push_back(1);
          res=tmp;
          for(auto a:res)
          {
              cout<<a<<' ';
          }
          cout<<endl;
     }
}   

 

posted @ 2015-08-27 20:31  Jessica程序猿  阅读(1346)  评论(0编辑  收藏  举报