删除无头链表的非尾节点
这个题还有一种出法:在O(1)时间复杂度下删除单链表节点(非表头节点或非尾节点)
void deleteNode(ListNode *node) {
ListNode* tmp = node->next;
node->val = tmp->val;
node->next = tmp->next;
delete tmp;
}
逆向打印单链表
这里有三种方法:
1,逆置单链表;
2,遍历单链表,将元素压入栈中,根据栈“先进后出”的性质来逆向打印单链表;
3,递归
方法一:
ListNode* ReverseShow(ListNode* head)
{
if(head == NULL) return NULL;
if(head->next == NULL) return head;
ListNode* cur = head;
ListNode* begin = head;
ListNode* last = head->next;
while(last)
{
cur = last;
last = last->next;
cur->next = begin;
begin = cur;
}
head->next = NULL; //单链表逆置完成
while(cur)
{
cout<<cur->val<<"->";
cur = cur->next;
}
cout<<endl;
}
方法二:
ListNode* ReverseShow(ListNode* head)
{
stack<int> s;
ListNode* cur = head;
while(cur)
{
s.push(cur->val);
cur = cur->next;
}
while(!s.empty())
{
cout<<s.top()<<"->";
s.pop();
}
}
方法三:
ListNode* ReverseShow(ListNode* head)
{
if(head == NULL)
return NULL;
ReverseShow(head->next);
cout<<head->val<<"->";
}