35翻转链表

来源:互联网 发布:广东专业seo外包公司 编辑:程序博客网 时间:2024/06/05 15:44

方法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;    

}