LeetCode:206. Reverse Linked List(单链表进行反转)

Reverse a singly linked list.

Example:


Input: 1->2->3->4->5->NULL           Output: 5->4->3->2->1->NULL


Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?


解法一(非递归方式):

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNode curr = head;
    while (curr != null) {
        ListNode nextTemp = curr.next;
        curr.next = prev;
        prev = curr;
        curr = nextTemp;
    }
    return prev;

时间复杂度:O(n)

空间复杂度:O(1)


解法二(递归的方式):

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}

时间复杂度:O(n)

空间复杂度:O(n)  ---递归需要额外的空间


利用C语言进行链表的反转:

1.利用非递归式:

Node* reverseList(Node* head){
    if(head==null||head->next==null){
        return head;   
    }
    Node * p=head;
    Node* newp=null;
    while(p!=null){
        Node* temp=p->next;  //存储一个临时位置
        p->next=newp;     // 将p的next域指向空
        newp=p;        // 新的指针指向
        p=temp;        // p指向下一个元素
    }
    return newp;
}

时间复杂度和空间复杂度同上

2.利用递归方式:

Node * reverseList(Node* head){
    if(head==null || head->next==null){ //如果它为空或者只有一个元素 ,就不变
        return head;
    }
    Node* newHead=reverseList(head->next);
    head->next->next=head;  //指正反过来指向
    head->next=null;   // 将自己指向空,防止出现异常
    return newHead;   // 返回最后newHead指针
}

时间复杂度和空间复杂度同上;

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/84032331