datawhale算法与数据结构(上)day2-顺序表和链表
task02: 顺序表和链表
- 理解线性表的定义与操作
- 实现顺序表
- 实现单链表、循环链表、双向链表
线性表的定义与操作
一、线性表的定义
线性表是逻辑上的抽象概念,是n个数据元素的有限序列。其中n为表长。表示如下:
a1是表头元素;an是表尾元素
- 除第一个元素外,每个元素有且仅有一个直接前驱,除最后一个元素外,每个元素有且仅有一个直接后继
- 元素的个数有限
- 表中元素具有逻辑上的顺序性,在序列中各元素排序有其先后次序
在稍复杂的线性表中,一个数据元素可以由若干个数据项组成,在这种情况下,常把数据元素称为记录,含有大量记录的线性表又称文件
二、线性表的基本操作
练习题
- 合并两个有序链表
https://leetcode-cn.com/problems/merge-two-sorted-lists/
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
/**
1. Definition for singly-linked list.
2. struct ListNode {
3. int val;
4. ListNode *next;
5. ListNode(int x) : val(x), next(NULL) {}
6. };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
ListNode* p = l1; //标记l1的头位置
ListNode* q = l2; //标记l2的头位置
ListNode* res = new ListNode(0); //创建返回列表的头节点
ListNode* r = res; //返回链表的尾节点
while(p&&q){
if(q->val>p->val){
r->next = p;
r = r->next;
p = p->next;
}
else{
r ->next = q;
r = r->next;
q = q->next;
}
}
if(q)
r->next = q;
if(p)
r->next = p;
return res->next;
}
};
- 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//快慢指针的问题
if(!head | !head -> next) return NULL;
ListNode* fast = head, *slow = head;
for(int i = 0; i< n; i++){
fast = fast -> next;
}
if(!fast){
return head->next;
}
while(fast->next){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};
- 旋转链表
https://leetcode-cn.com/problems/rotate-list/
给定一个链表,旋转链表,将链表每个节点向右移动k个位置,其中k是非负数。
示例 1:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode* p = head;
ListNode* re = NULL;
if(head == NULL) return head;
int count = 0;
while(p!=NULL){
count++;
re = p;
p = p->next;
}
int n = k % count;
re->next = head;
p = head;
for(int i = 0; i< count -n -1; i++){
p = p->next;
}
head = p->next;
p->next = NULL;
return head;
}
};
【来源】
[1]数据结构(c语言版)
[2]https://mp.weixin.qq.com/s/FZuBHkq8eOH459G6LoSTqw
[3]https://blog.youkuaiyun.com/u013733326/article/details/100332369