今天刷题时刷到了链表专题,但是平时习惯使用stl里面的list,导致以前学的模拟链表的相关知识都忘了,通过刷题也算是复习了一遍
以下所有习题来自lintcode
搜索插入位置
描述
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume NO duplicates in the array.
样例
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
class Solution {
public:
/**
* @param A: an integer sorted array
* @param target: an integer to be inserted
* @return: An integer
*/
int searchInsert(vector<int> &A, int target) {
for(int i=0;i<A.size();i++)
if(A[i]>=target)
return i;
return A.size();
}
};
在排序链表中插入一个节点
描述
Insert a node in a sorted linked list.
样例
Example 1:
Input: head = 1->4->6->8->null, val = 5
Output: 1->4->5->6->8->null
Example 2:
Input: head = 1->null, val = 2
Output: 1->2->null
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @param val: An integer.
* @return: The head of new linked list.
*/
public ListNode insertNode(ListNode head, int val) {
// write your code here
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = dummy;
while(p != null){
ListNode next = p.next;
if(next != null && next.val < val){
p = p.next;
}else{ //当p.val<val && next.val>val时代表找到插入节点的位置
ListNode newNode = new ListNode(val);
newNode.next = next;
p.next = newNode;
break;
}
}
return dummy.next;
}
}
链表的中点
给你一个链表,返回链表的中点
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: the head of linked list.
* @return: a middle node of the linked list
*/
ListNode * middleNode(ListNode * head) {
// write your code here
if(!head)
return NULL;
int len=0;
ListNode *s=head;
while(head)
{
len++;
head=head->next;
}
if(len%2==0)
len/=2;
else
len=len/2+1;
int p=1;
head=s;
while(head)
{
if(p==len)
return head;
head=head->next;p++;
}
}
};
链表节点计数II
返回链表中非负奇数的节点个数
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head:
* @return: nothing
*/
int countNodesII(ListNode * head) {
//
int ans=0;
while(head)
{
if(head->val>0&&head->val%2)
ans++;
head=head->next;
}
return ans;
}
};