LeetCode 20191124

1.两两交换链表中的节点
这道 最初想法是 利用奇偶不同 所以依次存储连续的节点 再排序
但是链表的本质 一个是值 另一个是指向的下一个节点 所以
关键在于重新排序这个链表 这个链子要重组
注意2:另外一点就是 需要重新整理这个链子 就要让有人指向头节点 所以做法是建立一个虚拟的头节点
注意3:每一次把三个节点揪出来进行重新排链子 就可以了

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head==NULL){return NULL;}
        ListNode* fake_head=new ListNode(0);
        fake_head->next=head;
        ListNode* cur=fake_head;
        while(cur->next!=NULL && cur->next->next!=NULL){
            ListNode* node1=cur->next;
            ListNode* node2=cur->next->next;
            ListNode* node_next=node2->next;
            cur->next=node2;
            node2->next=node1;
            node1->next=node_next;
            cur=node1;
        }
        return fake_head->next;
        
    }
};

2.删除排序数组中的重复项
好像不能使用remove()
所以 需要在循环中使用计数

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
       if(nums.size()==0){return 0;}
        int length=1;
       for(int i=0;i<nums.size();i++){
           if(nums[i]!=nums[length-1]){
               nums[length]=nums[i];
               length++;
           }
       }
       return length;
    }
};
发布了44 篇原创文章 · 获赞 9 · 访问量 3353

猜你喜欢

转载自blog.csdn.net/puying1/article/details/103230748
今日推荐