1. 移除元素
解题思路:
int removeElement(int* nums, int numsSize, int val){
int src = 0, dest = 0;
while(src < numsSize)
{
if(nums[src] != val)
{
nums[dest++] = nums[src++];
}
else
{
src++;
}
}
return dest;
}
2.删除排序数组中的重复项
解题思路:
int removeDuplicates(int* nums, int numsSize){
int dest = 0, src = dest+1;
while(src < numsSize)
{
if(nums[dest] == nums[src])
{
src++;
}
else
{
nums[++dest] = nums[src++];
}
}
return dest+1;
}
3.合并两个有序数组
解题思路:
void merge(int* nums1, int nums1Size, int m, int* nums2, int nums2Size, int n){
int end1 = m-1, end2 = n-1, end = m+n-1;
while(end1 >= 0 && end2 >= 0)
{
if(nums1[end1] < nums2[end2])
{
nums1[end--] = nums2[end2--];
}
else
{
nums1[end--] = nums1[end1--];
}
}
while(end2 >= 0)
{
nums1[end--] = nums2[end2--];
}
}
4.移除链表元素
思路一:原链表上进行修改
struct ListNode* removeElements(struct ListNode* head, int val){
//如果为空就返回空
if(head == NULL)
{
return NULL;
}
struct ListNode* cur = head;
struct ListNode* tail = NULL;
while(cur)
{
//当cur指向的值不为val时
if(cur->val != val)
{
tail = cur;
cur = cur->next;
}
//当cur指向的值为val时
else
{
//此时最开始的值就是val,改变head位置
if(tail == NULL)
{
head = cur->next;
free(cur);
cur = head;
}
else
{
struct ListNode* next = cur->next;
free(cur);
cur = next;
tail->next = cur;
}
}
}
if(tail)
tail->next = NULL;
return head;
}
思路二:增加一个哨兵位节点
struct ListNode* removeElements(struct ListNode* head, int val){
//哨兵位节点
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->next = NULL;
struct ListNode* cur = head;
struct ListNode* tail = newnode;
while(cur)
{
if(cur->val != val)
{
tail->next = cur;
cur = cur->next;
tail = tail->next;
}
else
{
struct ListNode* next = cur->next;
free(cur);
cur = next;
}
}
if(tail)
tail->next = NULL;
head = newnode->next;
free(newnode);
return head;
}
5.反转链表
思路一:定义一个newhead == NULL,然后将链表的节点从前往后进行头插:
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* newhead = NULL;
struct ListNode* cur = head;
while(cur)
{
struct ListNode* next = cur->next;
cur->next = newhead;
newhead = cur;
cur = next;
}
return newhead;
}
思路二:创建n1,n2,n3三个指针,通过改变他们指向,来反转:
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL)
{
return NULL;
}
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
struct ListNode* n3 = head->next;
while(n2)
{
n2->next = n1;
n1 = n2;
n2 = n3;
if(n3)
{
n3 = n3->next;
}
}
return n1;
}
6.返回链表的中间结点
思路:设置双指针。
当数量为奇数时,slow走一步,fast走两步,当slow走到中间时,fast走到最后,此时fast->next == NULL;
当数量为偶数时,slow走到中间位置,fast == NULL;
struct ListNode* middleNode(struct ListNode* head){
struct ListNode* slow = head;
struct ListNode* fast = head;
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
7.链表中倒数第k个结点
思路:设置双指针,如果fast不为空,让fast先走k步,slow与fast再都往后走。
struct ListNode* FindKthToTail(struct ListNode* pListHead, int k ) {
struct ListNode* slow = pListHead;
struct ListNode* fast = pListHead;
while(k--)
{
if(fast)
fast = fast->next;
else
return NULL;
}
while(fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}