35翻转链表

方法1:将单链表储存为数组,然后按照数组的索引逆序进行反转。

方法2:使用三个指针遍历单链表,逐个链接点进行反转。

/**
* Definition of ListNode
*
* class ListNode {
* public:
* int val;
* ListNode *next;
*
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
if(head==NULL||head->next==NULL)
{
return head;
}
ListNode*m=head;
ListNode*n=head->next;
ListNode*p;
head->next=NULL;
while(n)
{
p=n->next;
n->next=m;
m=n;
n=p;
}
head=m;
return head;// write your code here
}
};

方法3:从第2个节点到第N个节点,依次逐节点插入到第1个节点(head节点)之后,最后将第一个节点挪到新表的表尾。

ActList* ReverseList3(ActList* head)
{
ActList* p;
ActList* q;
p=head->next;
while(p->next!=NULL){
q=p->next;
p->next=q->next;
q->next=head->next;
head->next=q;
}

p->next=head;//相当于成环  
head=p->next->next;//新head变为原head的next  
p->next->next=NULL;//断掉环  
return head;    

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值