A--1-数据结构(1)--链表
B-链表专题(1)
题目
- 从尾到头打印链表
- 给定节点的值-删除链表中的节点
- 找链表的第一个相交节点
题目1 从尾到头打印链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
stack<ListNode*> ss;
vector<int> ans;
if( ! head )
return ans;
ListNode* cur = head;
while (cur )
{
ss.push(cur);
cur = cur->next;
}
while( ! ss.empty() )
{
ListNode* tmp = ss.top();
ss.pop();
ans.push_back(tmp->val);
}
return ans;
}
};
题目2 给定节点的值-删除链表中的节点
- 需要判断没有节点和只有一个节点的情况
- 两个指针,一个指针cur跟踪到要删除的节点
- 指针pre跟踪到删除节点的前驱节点
- 当删除节点是链表的为节点的时候,把 re节点的next设为nullptr
- 当删除节点不是尾节点的时候,把当前节点的val改成next的val,把当前节点的指针指向->next->next
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// 基于待删除的节点确实在链表中
ListNode* deleteNode(ListNode* head, int val) {
if ( ! head ){ return nullptr; }
if( head->next == nullptr && head->val ==val )
{
head = nullptr;
return head;
}
ListNode* cur = head;
ListNode* pre = head;
while ( cur->val != val )
{
pre = cur;
cur = cur->next;
}
if ( cur->next == nullptr )
{
pre->next = nullptr;
return head;
}
cur->val = cur->next->val;
cur->next = cur->next->next;
return head;
}
};
题目3 两个链表的第一个相交节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if ( headA == nullptr || headB == nullptr)
{
return nullptr;
}
ListNode* pa = headA;
ListNode* pb = headB;
// 计算两个链表的长度
int size_a = 0;
int size_b = 0;
while ( pa )
{
size_a++;
pa = pa->next;
}
pa = headA;
while ( pb )
{
size_b++;
pb = pb->next;
}
pb = headB;
// 步进
int step = 0;
if ( size_a > size_b)
{
step = size_a - size_b;
for ( int i = 0 ; i < step; ++i )
{
pa = pa->next;
}
}
if ( size_b > size_a)
{
step = size_b - size_a;
for ( int i = 0 ; i < step; ++i )
{
pb = pb->next;
}
}
// 找节点
while ( pa && pb )
{
if ( pa == pb )
{
return pa;
}
pa = pa->next;
pb = pb->next;
}
return nullptr ;
}
};
面试题24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if ( ! head || ! head->next )
{
return head;
}
stack<ListNode*> nodes;
ListNode* cur = head ;
while( cur != nullptr )
{
nodes.push(cur);
cur = cur->next;
}
ListNode* rehead = nodes.top();
ListNode* cur2 = rehead;
while ( nodes.size() >= 1 )
{
nodes.pop();
if (nodes.empty())
{
break;
}
cur2->next = nodes.top();
cur2 = cur2->next;
}
cur2->next = nullptr;
return rehead;
}
};
本文来自博客园,作者:longlongban,转载请注明原文链接:https://www.cnblogs.com/jiangxinyu1/p/12407655.html
简单学习分享,如有错误欢迎指正