leetcode-----链表-----反转链表

将一个链表反转:

/**

 * Definition for singly-linked list.

 * struct ListNode {

 *     int val;

 *     ListNode *next;

 *     ListNode(int x) : val(x), next(NULL) {}

 * };

 */

class Solution {

public:

    ListNode* reverseList(ListNode* head) {

        ListNode *a,*r,*s;

        a=head;

        r=a;

        if(head!=NULL&&head->next!=NULL){

        while(a->next->next!=NULL&&a->next!=NULL){

            s=a->next->next;

            r=a->next;

            a->next->next=head;

            a->next=s;

            head=r;  

        }

        if(a->next->next==NULL){

            a->next->next=r;

            r=a->next;

            head=r;

            a->next=NULL;

        }

        

        }

        return head;

    }

};

//*********************************************************************************************************************************************************************


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
		if(head==NULL)
			return head;
       if(head->next==NULL)	//链表为空的情况
		  return head;
		  
	   ListNode *p=NULL,*r=NULL,*s=NULL;
	   p=head;	//将p移到第一个存储数据
        s=head;
        int temp=0;;
        
        if(p->next->next==NULL){    // 两个结点的情况,直接交换值
           temp=p->val;
           p->val=p->next->val;
           p->next->val=temp;
           return head;
	  }
        
	  
	  while(p->next!=NULL&&p->next->next!=NULL){	//除了头结点外多于两个结点的情况
		  r=p->next->next;              
		  p->next->next=s;
          s=p->next;
          p->next=r;
	  }
	   p->next->next=s;
       s=p->next;
       p->next=NULL;
         
	   
	   return s;
	   
	   
    }
};

猜你喜欢

转载自blog.csdn.net/xuchen1230/article/details/80176128