数据结构与算法 - 单链表逆转

Posted 极客学伟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构与算法 - 单链表逆转相关的知识,希望对你有一定的参考价值。

数据结构与算法 - 单链表逆转

单链表逆转输出

方案一:head 作为已知首节点,最后节点指向null, 使用三个指针便利链表,逐个节点进行反转

实现代码:

struct ActList 
    ActList * next;
;

ActList * reverseList(ActList * head) 
    
    if (head == NULL || head -> next == NULL) 
        // 少于两个节点无需反转
        return head;
    
    
    ActList * p;
    ActList * q;
    ActList * r;
    
    p = head;
    q = head -> next;
    head -> next = NULL;
    
    while (q) 
        r = q -> next;
        q -> next = p;
        
        p = q;
        q = r;
    
    
    head = p;
    
    return head;

方案二: 对于一条链表,从第2个节点到第N个节点,依次逐节点插入到第1个节点(head节点)之后,(N-1)次这样的操作结束之后将第1个节点挪到新表的表尾

代码:

ActList* ReverseList2(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;  


方案三:循环

ActList * reverseList3 (ActList * head) 
    if (head == NULL || head -> next == NULL) 
        // 少于两个节点无需反转
        return head;
    
    
    ActList *pre = NULL;
    ActList *next = NULL;
    while (head != NULL) 
        next = head -> next;
        head -> next = pre;
        
        pre = head;
        head = next;
    
    
    return pre;

public ListNode reverseList2(ListNode head) 

	if (head == null || head.next == null) return head;
	ListNode newHeaderListNode = null;
	while (head != null) 
		ListNode tempListNode = head.next;
		head.next = newHeaderListNode;
		newHeaderListNode = head;
		head = tempListNode;
	
	return newHeaderListNode;

方案四: 递归

ActList * reverseList4 (ActList * head) 
    if (head == NULL || head -> next == NULL) 
        // 少于两个节点无需反转
        return head;
    
    ActList *newHead = reverseList4(head -> next);
    
    head -> next -> next = head;
    head -> next = NULL;
    
    return newHead;

public ListNode reverseList(ListNode head)

	if (head == null || head.next == null) return head;
	ListNode newHeaderListNode = reverseList(head.next);
	head.next.next = head;
	head.next = null;
	return newHeaderListNode;

以上是关于数据结构与算法 - 单链表逆转的主要内容,如果未能解决你的问题,请参考以下文章

PTA-数据结构与算法基础题目集(中文)

单链表逆转问题

算法与数据结构索引

6-1 单链表逆转

6-1 单链表逆转(20 分)

List习题单链表逆转